Mat*_*iby 2 ruby ruby-on-rails
我在我正在处理的一些代码中找到了这个,我想知道这是做什么的
h = Hash.new {|hash, key| hash[key] = 0}
=> {}
Run Code Online (Sandbox Code Playgroud)
Hash.new每次访问不存在的密钥时,都会调用块传递给该块.例如:
h = Hash.new { |hash, key| hash[key] = "Default" }
h[:defined_key] = "Example"
puts h[:defined_key] # => "Example"
puts h[:undefined_key] # => "Default"
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参见http://ruby-doc.org/core/classes/Hash.html#M000718.