Overlooked Feature of Ruby Hashes
Wednesday November 09 2005, 11:08 AM
Noticed on ruby-talk:
When you create a Hash object in Ruby, you have the option of providing a block; when a hash lookup fails, this block will be called and its result returned instead of nil. The block is passed two parameters: the hash itself, and the requested key.
For example:
h = Hash.new { |h, k|
"You asked for #{k}. #{k} is not here."
}
puts h["Zordo"] # => You asked for Zordo. Zordo is not here.
# See! The hash is not modified by the callback, though
p h # => {}
# But it can be...
h2 = Hash.new { |h, k|
puts "I sing of spleen."
h[k] = "Respond, o ye #{k}!"
"Hear me!"
}
puts h2["kumquats"] # => I sing of spleen.
Hear me!
# This time the lookup succeeds:
puts h2["kumquats"] # => Respond, o ye kumquats!