Ruby:如何从Hash填充Hash的子类
我正在创建一个hash的子类,我希望能够首先使用hash填充它,即:Ruby:如何从Hash填充Hash的子类,ruby,Ruby,我正在创建一个hash的子类,我希望能够首先使用hash填充它,即: class HashSub < Hash def initialize(old_hash) ... end end a = HashSub.new({'akey' => 'avalue'}) puts a['akey'] >> avalue class HashSub'avalue'}) 放一个['akey'] >>阿瓦鲁 既然Hash.new不接受散列,那么实现这一点最干净的
class HashSub < Hash
def initialize(old_hash)
...
end
end
a = HashSub.new({'akey' => 'avalue'})
puts a['akey']
>> avalue
class HashSub'avalue'})
放一个['akey']
>>阿瓦鲁
既然
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
>类SubHash零
>>a=散列[{:a=>:b}]
=>{:a=>:b}
>>a.课堂
=>散列
>>b=次灰[{:a=>:b}]
=>{:a=>:b}
>>b级
=>次灰分
根据我的经验,最干净的方法是不使用初始值设定项,而是依赖类“[]
运算符:
>> class SubHash < Hash; end
=> nil
>> a = Hash[{:a => :b}]
=> {:a=>:b}
>> a.class
=> Hash
>> b = SubHash[{:a => :b}]
=> {:a=>:b}
>> b.class
=> SubHash
>类SubHash零
>>a=散列[{:a=>:b}]
=>{:a=>:b}
>>a.课堂
=>散列
>>b=次灰[{:a=>:b}]
=>{:a=>:b}
>>b级
=>次灰分
要改进Denis的答案,您可以将class方法[]
别名为new
class SubHash < Hash; end
singleton_class{alias :new :[]}
end
SubHash.new(a: :b).class # => SubHash
class SubHashSubHash
要改进Denis的答案,您可以将class方法[]
别名为new
class SubHash < Hash; end
singleton_class{alias :new :[]}
end
SubHash.new(a: :b).class # => SubHash
class SubHashSubHash