From: Martin DeMello Date: 2006-07-14T18:00:29+09:00 Subject: Re: Recursion and Ruby On 7/14/06, Glenn Cadman wrote: > Daniel Martin wrote: > > > > $fib = Hash.new{|h,k| h[k] = h[k-2] + h[k-1]} > > $fib[0] = 0 > > $fib[1] = 1 > > Well whilst my orginal exercise was just to get recursion working in > ruby, I have to say this solution is very quick to calculate any result > and is recursive in a way that is quite "foriegn" to me. The problem for > me is that I find it difficult to understand what is happening in this > code. I would have though the stack would collapse due to referencing > something that is not defined yet. eg. h[k-2] for example in the intial > state of the $fib hash would not be found unless the k was 3 or 2. eg > $fib(30) would return "I dont have any thing to reference for h[30] = > h[28] + h[29], has h[28] and h[29] havent been defined. The block form of Hash.new calls the block for every nonexistent-hash-key access. So $fib[30] looks for the key 30, doesn't find it, and calls the block instead, passing it $fib and 30. The block tries to return h[29] + h[28], but since they don't exist either, the calls to [] will again call the block, and so on. martin