Mega Code Archive

 
Categories / Ruby / Hash
 

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