最初にハッシュを使用して入力できるようにしたい、ハッシュのサブクラスを作成しています。
class HashSub < Hash
def initialize(old_hash)
...
end
end
a = HashSub.new({'akey' => 'avalue'})
puts a['akey']
>> avalue
Hash.new
ハッシュを取らないので、これを達成する最もクリーンな方法は何ですか?
最初にハッシュを使用して入力できるようにしたい、ハッシュのサブクラスを作成しています。
class HashSub < Hash
def initialize(old_hash)
...
end
end
a = HashSub.new({'akey' => 'avalue'})
puts a['akey']
>> avalue
Hash.new
ハッシュを取らないので、これを達成する最もクリーンな方法は何ですか?
私の経験では、最もクリーンなのは、初期化子をそのままにして、クラスの[]
演算子に依存することです。
>> class SubHash < Hash; end
=> nil
>> a = Hash[{:a => :b}]
=> {:a=>:b}
>> a.class
=> Hash
>> b = SubHash[{:a => :b}]
=> {:a=>:b}
>> b.class
=> SubHash
Denis の回答を改善するために、クラス メソッド[]
を にエイリアスできますnew
。
class SubHash < Hash; end
singleton_class{alias :new :[]}
end
SubHash.new(a: :b).class # => SubHash
H = Class.new Hash
a = {a: 2, b: 3}
b = H[ a ]
b.class #=> H