From: Tim Hunter Date: 2008-06-26T01:05:20+09:00 Subject: Re: Question on passing blocks Ruby Freak wrote: > In the code below, a block, { x += 1 } is magically passed to > thrice ?? or something like that. > I don't understand the usage of the "thrice { iterator }" using {} > and why I can't make a normal block syntax work. The thrice method > doesn't take (normal) parameters, so how does this work? > > Ruby, Have you been messing around behind my back? > Thanks in advance. > > def thrice > yield > yield > yield > end > > x = 5 > puts "value of x before: #{x}" # => 5 > thrice { x += 1 } > puts "value of x after: #{x}" # => 8 > > # broken from here down > > thrice { |x| x += 1 } > > thrice do |x| > x += 1 > end In the first case, x in the block refers to the x defined outside the block. In the 2nd and 3rd cases, you've used x as an argument so it hides the x outside the block. Any changes you make to x-the-argument are lost each time the block exits. -- Posted via http://www.ruby-forum.com/.