Reputation: 7172
I have a regular hash
myhash = { :abc => 123 }
and a class
class SpecialHash < Hash
def initialize arg_hash
# how do I say
self = arg_hash
end
end
or
Is there some way of doing: myhash.class = SpecialHash?
-daniel
Upvotes: 1
Views: 54
Reputation: 176362
The best solution depends on the library you want to extend and on what you are trying to achive.
In case of a Hash, it's quite hard to extend it in that way because there is no initializer you can override when you use the Ruby hash syntax.
However, because creating a new hash with some value is the same of merging an empty hash with the given values, you can do
class SpecialHash < Hash
def initialize(hash)
self.merge!(hash)
end
end
myhash = SpecialHash.new(:abc => 123)
myhash
will then be an instance of SpecialHash
with the same properties of a Hash.
Notice the use of merge!
that is actually changing the value of self
. Using self.merge
will not have the same effect.
Upvotes: 1