我想使用哈希作为更大哈希的默认值。但我不知道如何通过外部哈希设置内部哈希的值。
h = Hash.new do
{:counter => 0}
end
h[:a][:counter] += 1
=> 1
h[:a][:counter] += 1
=> 1
h[:a][:counter] += 1
=> 1
h
=> {}
呃,这是正确的方法吗?
答案 0 :(得分:4)
如果你是initialize with a default value哈希:
h = Hash.new({:counter => 5})
然后您可以按照示例中的调用模式进行操作:
h[:a][:counter] += 1
=> 6
h[:a][:counter] += 1
=> 7
h[:a][:counter] += 1
=> 8
或者,您可能希望使用块初始化,以便每次使用新密钥时都会创建:counter
哈希的新实例:
# Shared nested hash
h = Hash.new({:counter => 5})
h[:a][:counter] += 1
=> 6
h[:boo][:counter] += 1
=> 7
h[:a][:counter] += 1
=> 8
# New hash for each default
n_h = Hash.new { |hash, key| hash[key] = {:counter => 5} }
n_h[:a][:counter] += 1
=> 6
n_h[:boo][:counter] += 1
=> 6
n_h[:a][:counter] += 1
=> 7
答案 1 :(得分:0)
def_hash={:key=>"value"}
another_hash=Hash.new(def_hash)
another_hash[:foo] # => {:key=>"value"}