Stefan
Stefan

Reputation: 9329

Ruby: How to populate subclass of Hash from Hash

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?

Upvotes: 2

Views: 232

Answers (3)

sawa
sawa

Reputation: 168091

To improve on Denis' answer, you can alias the class method [] to new.

class SubHash < Hash; end
  singleton_class{alias :new :[]}
end

SubHash.new(a: :b).class # => SubHash

Upvotes: 2

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

H = Class.new Hash
a = {a: 2, b: 3}
b = H[ a ]
b.class #=> H

Upvotes: 0

Denis de Bernardy
Denis de Bernardy

Reputation: 78443

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

Upvotes: 7

Related Questions