From: Gregory Seidman Date: 2008-04-10T23:27:43+09:00 Subject: Re: What should this print? On Thu, Apr 10, 2008 at 11:15:04PM +0900, Boson wrote: > With more context: > > It's interesting that these two product different output: > > old = nil > [1,1].each do |n| > if n != old > x = 1 > old = n > end > p x > end > > old = nil > for n in [1,1] > if n != old > x = 1 > old = n > end > p x > end It's not especially interesting. The block passed to each has a local variable, x, which is nil in the second iteration because it has never been set. The for loop does not create a new scope, thus the x variable retains the value it was set to in the previous iteration, i.e. 1. Amusingly, if you run the two in the same Ruby instance in the opposite order (the for loop first), you'd see identical output because in that case x would have been declared in the outer scope and the block would be using that x by closure. --Greg