From: Alex Young Date: 2007-11-14T19:47:17+09:00 Subject: Re: recursion with blocks Douglas A. Seifert wrote: > Pat Maddox wrote: >> On Nov 13, 2007 4:15 PM, James Edward Gray II >> wrote: >> >>> On Nov 13, 2007, at 6:01 PM, Mike Perham wrote: >>> >>> >>>> You aren't actually recursing inside the block, >>>> just using the block as a conditional. I was trying to figure out how >>>> to recurse inside the block. >>>> >>> Yeah, I was just using the block inside a recursive method. You are >>> right. >>> >>> Can you elaborate on what you mean by "recurse inside a block?" I'm >>> having trouble thinking of an example. >>> >>> James Edward Gray II >>> >>> >>> >> >> I think he means something like this? >> >> fact = lambda {|val| return 1 if val <= 0; val * fact[val - 1] } >> fact[4] => 24 >> >> but I'm not sure... >> >> Pat >> >> > This works: > > irb(main):001:0> fact = lambda {|val| val <= 0 ? 1 : val * fact[val-1] } Another example I coincidentally came up with for another thread, looking at how the stack is printed on 1.8 and 1.9: $ ruby -e "a = Proc.new{|d| raise 'foo' if d==0; a.call(d-1)}; a.call(20)" -e:1: foo (RuntimeError) from -e:1:in `call' from -e:1 from -e:1:in `call' from -e:1 from -e:1:in `call' from -e:1 from -e:1:in `call' from -e:1 ... 30 levels... from -e:1:in `call' from -e:1 from -e:1:in `call' from -e:1 -- Alex