ruby:使用散列作为另一个散列的默认值?
我想使用散列作为更大的散列的默认值。但是我不知道如何通过外部散列设置内部散列的值ruby:使用散列作为另一个散列的默认值?,ruby,hash,Ruby,Hash,我想使用散列作为更大的散列的默认值。但是我不知道如何通过外部散列设置内部散列的值 h = Hash.new do {:counter => 0} end h[:a][:counter] += 1 => 1 h[:a][:counter] += 1 => 1 h[:a][:counter] += 1 => 1 h => {} 嗯,正确的方法是什么?如果你想要一个哈希: h = Hash.new({:counter => 5}) 然后,您可以遵循示例
h = Hash.new do
{:counter => 0}
end
h[:a][:counter] += 1
=> 1
h[:a][:counter] += 1
=> 1
h[:a][:counter] += 1
=> 1
h
=> {}
嗯,正确的方法是什么?如果你想要一个哈希:
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
如果您需要一个散列:
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