I found this in my some code I was working on and I was wondering what this is doing
h = Hash.new {|hash, key| hash[key] = 0}
=> {}
When a block is passed to Hash.new that block is called each time a non-existent key is accessed. Eg:
h = Hash.new { |hash, key| hash[key] = "Default" }
h[:defined_key] = "Example"
puts h[:defined_key] # => "Example"
puts h[:undefined_key] # => "Default"
See http://ruby-doc.org/core/classes/Hash.html#M000718 for more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With