Hash.new with block logic : Hash.new « Hash « Ruby






Hash.new with block logic


p h = Hash.new { |hash, key| (key.respond_to? :to_str) ? "nope" : nil }
p h[1]                                           # => nil
p h['do']                   # => "nope"

 








Related examples in the same category

1.Creating Hashes
2.You can test to see if a hash is empty with empty?
3.Test how big it is with length or size
4.use new to create a hash with a default value which is otherwise just nil
5.access any key in a hash that has a default value
6.Hash with =>
7.This lazily initialized hash maps integers to their factorials