From: "List.rb" Date: 2008-11-13T15:14:35+09:00 Subject: Re: Issue with block and getting to local variables One thing with locals that got me is that you have to define them first so the /parser?/ doesn't bail. I.e ### breaks: lamb = lambda { a+b } a = 1 b = 2 p lamb.call You must put a,b = nil,nil before the lambda definition :-/ ( sorry for top post, on iphone just realized it, no clipboard ) On Nov 12, 2008, at 10:47 PM, "Eric I." wrote: > On Nov 12, 5:59 pm, Tarek Other wrote: > >> >> i.e.) I want to know if there is a way to call the block such that it >> knows or has access to all the local variables of the caller without >> having to pass those local variables in. > > Hi Tarek, > > Yes, this is the standard behavior of blocks. Blocks are closures, > which means that they have access to the surrounding environment. > > For example, this code works just fine, even though "y" is a local > variable used set outside the block and used inside the block: > > ==== > > def method1(&block) > 0.upto(12) do |v| > yield v > end > end > > def method2(y) > method1 do |z| > puts "#{y} * #{z} = #{y * z}" > end > end > > puts "Let's do the 3 times tables:" > method2(3) > > ==== > > I hope that helps, > > Eric > > ==== > > Are you looking for on-site Ruby or Ruby on Rails training > that's been highly reviewed by former students? > http://LearnRuby.com > >