From: Douglas Livingstone Date: 2005-06-13T11:35:55+09:00 Subject: Re: Only if the object exists On 6/12/05, Gavin Kistner wrote: > def foo > 10.times{ i = i ? i+1 : 1 } > puts i = i ? i+1 : 1 > 10.times{ i = i ? i+1 : 1 } > puts i = i ? i+1 : 1 > end > > results in "1" and "12" being written, instead of "11" and "22". > > Ruby is the first language I've seen where the scope of a variable is > not the same throughout the same block. { i = i ? i+1 : 1 } is a new block. Setting i inside this block doesn't bubble up to the parent unless i is already defined. Compare with: def bar i = 0 10.times{ i = i ? i+1 : 1 } puts i = i ? i+1 : 1 10.times{ i = i ? i+1 : 1 } puts i = i ? i+1 : 1 end I'd call it a bug, we'll see if it still happens in Ruby2. Duglas