Created
June 20, 2012 13:53
-
-
Save ccooke/2959994 to your computer and use it in GitHub Desktop.
String/Hash/Array self-destruction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Considered adding this to Object, but that's a much more complex job. This gets the work done. | |
class Hash | |
def self_destruct! | |
self.each do |k,v| | |
v.self_destruct! if v.respond_to? :self_destruct! | |
self[k] = nil | |
self.delete k | |
end | |
end | |
end | |
class Array | |
def self_destruct! | |
self.each_with_index do |v,i| | |
v.self_destruct! if v.respond_to? :self_destruct! | |
self[i] = nil | |
self.delete i | |
end | |
end | |
end | |
class String | |
def self_destruct! | |
return if self.empty? | |
ObjectSpace.each_object(String).select { |o| o == self }.each do |string_copy| | |
next unless string_copy.object_id != self.object_id | |
next if string_copy.frozen? | |
string_copy.replace "" | |
end | |
self.replace "" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment