From: Patrick Hurley Date: 2006-07-14T23:24:14+09:00 Subject: Re: Recursion and Ruby > On 7/14/06, Glenn Cadman wrote: > > The problem for > > me is that I find it difficult to understand what is happening in this > > code. When I am confused (which happens all too often), I like to "see" what is happening. Below is the same algorithm with a slightly different implementation (I used class variables rather than a global). I also provided a simple accessor to the class variable. Good Luck pth class Integer @@fib = Hash.new do |h,k| puts "Calculate fib[#{k}]" h[k] = h[k-2] + h[k-1] end @@fib[0] = 0 @@fib[1] = 1 def fib @@fib[self] end def self.fibs @@fib end end puts 10.fib puts 7.fib.fib p Integer.fibs ----- Output ------ Calculate fib[10] Calculate fib[8] Calculate fib[6] Calculate fib[4] Calculate fib[2] Calculate fib[3] Calculate fib[5] Calculate fib[7] Calculate fib[9] 55 Calculate fib[13] Calculate fib[11] Calculate fib[12] 233 {5=>5, 11=>89, 0=>0, 6=>8, 12=>144, 1=>1, 7=>13, 13=>233, 2=>1, 8=>21, 3=>2, 9=>34, 4=>3, 10=>55}