From: Adam Prescott Date: 2011-05-24T19:08:13+09:00 Subject: Re: "Local variable within code blocks do not interfere with those outside the block" --20cf301cc3c2f25c7b04a402c3a9 Content-Type: text/plain; charset=UTF-8 On Tue, May 24, 2011 at 10:45 AM, Kaye Ng wrote: > " In Ruby 1.9, however, local variables used within code blocks will not > interfere with local variables located outside of the block." > > I don't know if my code is wrong, but it looks to me like the local > variable inside the code block DOES interfere with the local variable > (with the same name) outside the code block. > > x = [1, 2, 3, 4, 5] > var = 1 > > x.each do > |number| (var = 10) > end > > puts var > It's affecting `var` because of the assignment, and because it's not an argument to the block. You might find http://ruby.runpaint.org/closures#block-local-variables useful to read through. Also consider this: a = 1; [2].each { |x| p a }; a #=> 1; 1 a = 1; [2].each { |x| a = 10; p a }; a #=> 10; 10 a = 1; [2].each { |a| p a }; a #=> 2; 1 a = 1; [2].each { |a| p a; a = 10; p a }; a #=> 2; 10; 1 And with block-local variables in 1.9: a = 1; [2].each { |;a| p a; }; a #=> nil; 1 a = 1; [2].each { |;a| p a; a = 2; p a }; a #=> nil; 2; 1 --20cf301cc3c2f25c7b04a402c3a9--