2012-07-06 197 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"} 
相關問題