Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby hash setup

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}
 => {} 
like image 657
Matt Elhotiby Avatar asked Apr 22 '26 09:04

Matt Elhotiby


1 Answers

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.

like image 96
dnch Avatar answered Apr 23 '26 23:04

dnch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!