From: Justin Collins Date: 2008-01-10T10:33:02+09:00 Subject: Re: problem with closure/block levilista@gmail.com wrote: > ########################### > y=5 > print "y: " + y.to_s + "\n" > text_at_the_end = lambda do |y| > print y + " text at the end\n" > end > > print "y: " + y.to_s + "\n" > > > def oneparam > yield("oneparam") > end > > oneparam(&text_at_the_end) > print "y: " + y + "\n" > > > ######################## > It gives the following output: > > y: 5 > y: 5 > oneparam text at the end > y: oneparam > > > Is this a bug? Shouldn't "y" be in a local scope in "text_at_the_end"? > I just downloadad Ruby yesterday: > > Ruby Version 1.8.6 > Installer Version 186-2 Blocks in Ruby are closures, so they save the context in which they were created, but new variables inside the closure are local. irb(main):001:0> x = 1 => 1 irb(main):002:0> l = lambda do |y| irb(main):003:1* puts x irb(main):004:1> puts y irb(main):005:1> end => # irb(main):006:0> l['hello'] 1 hello => nil irb(main):007:0> y NameError: undefined local variable or method `y' for main:Object from (irb):7 from :0 irb(main):008:0> x => 1 irb(main):009:0> x += 1 => 2 irb(main):010:0> l['again'] 2 again => nil Take a look here: http://ruby-doc.org/docs/ProgrammingRuby/html/tut_containers.html#UG -Justin