Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby:如何从Hash填充Hash的子类_Ruby - Fatal编程技术网

Ruby:如何从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不接受散列,那么实现这一点最干净的

我正在创建一个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 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