On 11/05/2013 03:42 PM, Stefan Salewski wrote:
> irb(main):009:0* 5.times{|i; j| if i == 0 then j = 1 end; print i, j,
> "\n"}
> 01
> 1
> 2
> 3
> 4
> => 5
>
> I read about the behaviour of blocks and variables in "The Ruby
> Programming Language" but can not really remember this topic for loops
> -- it really surprises me. (I found a similar question at
> stackoverflow.com, but no good answer.)
>
> So Ruby 1.9.3 forgets all local variable values for each loop iteration.
> Good to know this. Was it mentioned clearly in the documentation or the
> textbooks? And for what is this behaviour in loops really good? I am
> really happy that it took me only 10 minutes to find that problem in my
> code, I should try to keep it in my head. ( Of course the solution, as
> mentioned in Matz's book, is simple a j=0 in front of the loop.)
>
> Best regards
>
> Stefan Salewski
>
>

This is a block, just like any other block. The code is explicitly 
setting j to be a block local variable, so each time the block is 
invoked it is a fresh variable. There is no difference between your code 
and this code, assuming j is not an existing variable:

5.times{|i| j = nil; if i == 0 then j = 1 end; print i, j, "\n"}

(Actually, you don't even need `j = nil`, but that's more of an accident 
of Ruby's implementation.)

Just like one wouldn't expect a variable local to a method to persist 
each time the method is called, neither does a variable local to a 
block. The difference is that a block is also a closure, so it can 
reference and manipulate variables in the scope surrounding it.

-Justin