I'm making a subclass of hash, which I want to be able to populate initially using a hash, i.e.:
class HashSub < Hash
def initialize(old_hash)
...
end
end
a = HashSub.new({'akey' => 'avalue'})
puts a['akey']
>> avalue
Since Hash.new doesn't take a hash, what's the cleanest way to achieve this?
The cleanest, in my experience, is to leave the initializer alone and to rely the class' [] operator:
>> class SubHash < Hash; end
=> nil
>> a = Hash[{:a => :b}]
=> {:a=>:b}
>> a.class
=> Hash
>> b = SubHash[{:a => :b}]
=> {:a=>:b}
>> b.class
=> SubHash
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With