From: "David A. Black" Date: 2008-12-06T02:19:32+09:00 Subject: Re: Ruby 1.8.7 Lambas: syntax and scoping issue (are these bugs? Hi -- On Sat, 6 Dec 2008, Charlton Wang wrote: > I'm seeing two odd behaviours with using lambdas: I'm skipping to #2 if that's OK. > 2. I'm not understanding the scoping rules for lambda with > instance_evals inside a class: > > # If these statements are added at the beginning the > # the lambda will evaluate them first > # a = 4 # stmt 1 > # b = 5 # stmt 2 > class Bar > attr_accessor :a, :b > def initialize > @a = 1 > @b = 2 > end > def foo(&block) > instance_eval(&block) > end > end > > m = lambda{puts a + b} > Bar.new.foo(&m) > > Without stmt1 and stmt2 above, the code correctly outputs 3. But if > stmt1 and stmt2 are incommented, the output is 9 which seems to be the > global scope rather than the scope of the instance of Bar expected > with instance_eval. > > Am I missing something? When Ruby sees a and b, it favors the interpretation that they are local variables. If you want to ensure that they're interpreted as method calls, you can do: puts a() + b() David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS (Jan 12-15), Fort Lauderdale, FL See http://www.rubypal.com for details Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2)