1

我想使用散列作为更大散列的默认值。但我不知道如何通过外散列设置内散列的值。

h = Hash.new do 
  {:counter => 0}
end
h[:a][:counter] += 1
=> 1 
h[:a][:counter] += 1
=> 1
h[:a][:counter] += 1
=> 1 
h
=> {}

呃,正确的方法是什么?

4

2 回答 2

4

如果您使用哈希的默认值进行初始化:

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 
于 2012-07-06T02:39:45.113 回答
0
def_hash={:key=>"value"}
another_hash=Hash.new(def_hash)
another_hash[:foo] # => {:key=>"value"}
于 2013-05-24T11:09:35.923 回答