From: "David A. Black" Date: 2007-10-15T01:29:29+09:00 Subject: Re: Parameter in a block is not local? Hi -- On Sun, 14 Oct 2007, SpringFlowers AutumnMoon wrote: > I thought a iterator with a block is like an nameless function call... > so if it is a function call, the parameter is local. > but for the following, the output is surprising: > > a = 1 > p a > > 1.upto(10) {|a| p a} > > p a > > -------------- > > E:\>ruby test_iterator.rb > 1 > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > 10 > 10 > > a is changed! > > but is it true that the "a" is not global to begin with.... > but then, isn't the "a" inside the block more local than the "a" > outside? a is local, not global. The semantics of block parameters is assignment semantics: |a| basically means "a = ...", in the same scope as the scope in which the block is created. Blocks are different in that respect from methods, and the || notation (instead of (), as in methods) is a good reminder that they're not the same. (Not that || specifically implies assignment semantics, but it's a reminder that there's a difference.) David -- Upcoming training from Ruby Power and Light, LLC: * Intro to Ruby on Rails, Edison, NJ, October 23-26 * Advancing with Rails, Edison, NJ, November 6-9 Both taught by David A. Black. See http://www.rubypal.com for more info!