From: "vidar.hokstad@..." Date: 2006-02-07T20:38:21+09:00 Subject: Re: lazy evaluation? Martin DeMello wrote: > Could someone explain why this code works: > > def repeat(condition) > puts "condition: #{condition}" > yield > retry if not condition > end > > j=0 > repeat (j >= 10) do > puts j > j+=1 > end > > puts "after loop, j = #{j}" > > I'd have expected repeat (j >= 10) to pass "false" into the method, > which would then yield repeatedly to the do/end block, never seeing the > (condition) part again. It's your assumption of where the "retry" restarts execution that's wrong... Essentially the retry in "repeat" will restart execution right before the call to repeat, not at the start of the "repeat" method, thus evaluating the arguments again. You can see that by changing your code so that there's an observable side effect of the reevaluation: #### def cond(c) puts "Reevaluating the condition" c end def repeat(condition) puts "condition: #{condition}" yield retry if not condition end j=0 repeat (cond(j >= 10)) do puts j j+=1 end puts "after loop, j = #{j}" #### It surprised me too, but it is much more useful that way. Vidar