我做散列的一个子类,我希望能够以填充最初使用的哈希,即:红宝石:如何填充哈希的子类,从哈希
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
H = Class.new Hash
a = {a: 2, b: 3}
b = H[ a ]
b.class #=> H
为了提高对丹尼斯的回答,您可以别名类方法[]
到new
。
class SubHash < Hash; end
singleton_class{alias :new :[]}
end
SubHash.new(a: :b).class # => SubHash