This lazily initialized hash maps integers to their factorials : Hash.new « Hash « Ruby






This lazily initialized hash maps integers to their factorials


fact = Hash.new {|h,k| h[k] = if k > 1: k*h[k-1] else 1 end }
p fact      # {}: it starts off empty
p fact[4]   # 24: 4! is 24
p fact      # {1=>1, 2=>2, 3=>6, 4=>24}: the hash now has entries

 








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.Hash.new with block logic