2012-07-06 141 views

回答

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 
0
def_hash={:key=>"value"} 
another_hash=Hash.new(def_hash) 
another_hash[:foo] # => {:key=>"value"} 
相关问题