Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to populate subclass of Hash from Hash

Tags:

ruby

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?

like image 621
Stefan Avatar asked Dec 05 '25 07:12

Stefan


1 Answers

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
like image 80
Denis de Bernardy Avatar answered Dec 07 '25 02:12

Denis de Bernardy