Matt Elhotiby
Matt Elhotiby

Reputation: 44086

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}
 => {} 

Upvotes: 2

Views: 165

Answers (3)

dnch
dnch

Reputation: 9605

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.

Upvotes: 7

Chris Cherry
Chris Cherry

Reputation: 28574

Its making the default values for any new keys equal to zero instead of nil, observe the test in and irb console session:

$ irb
>> normal_hash = Hash.new
=> {}
>> normal_hash[:new_key]
=> nil
>> h = Hash.new {|hash, key| hash[key] = 0}
=> {}
>> h[:new_key]
=> 0

Upvotes: 0

Thomas Andrews
Thomas Andrews

Reputation: 1597

http://ruby-doc.org/core/classes/Hash.html#M000718

This block defines what the hash does when accessing a nonexistent key. So if there is no value for a key, then it sets the value to 0, and then returns 0 as the value.

It's not just good for defaults - you could have it throw an exception of there is no such key, for example. In fact, if you just want a default value, you can say:

Hash.new "defaultValue"

Upvotes: 2

Related Questions