From: "trans. (T. Onoma)" Date: 2004-12-03T15:02:49+09:00 Subject: Re: nested defs, what if... Hi -- On Friday 03 December 2004 12:18 am, nobu.nokada@softhome.net wrote: | Gavin Sinclair wrote in [ruby-talk:122305]: | > > class A | > > def a(y) | > > def b(x) | > > x + y # `y' in a or `undefined local variable'? | > > end | > > 10.times{ |i| print b(i) } | > > end | > > end | > | > Is there any difference between an "inner method" (with 'y' in a) and | > a lambda? | | Actually, no. Just a syntax sugar, and it would be implemented | using a lambda. And another question; should b be visible from | other methods called from a? First, it is debatable as to whether `y' should have an open scope like a lambda. But I think "no". def a() cannot see vars outside its scope either, so nor should def b(). This gives good inner namespace protection and differentiates its functionality from a lambda. Second, b() should not be visible from other methods just a local vars are not visible. I am surprised to hear they would be implemented using lambdas. I was under the impression that implementation of Procs and Methods are quite different. | > I've happily used lambdas to define private functionality before, but | > I'm concerned about efficiency: | > | > class A | > def a(y) | > b = lambda { |x| x + y } | > 10.times { |i| print b(i) } | > end | > end | > | > Does the lambda attached to b get regenerated with each call to a? Yes, I think so since lambdas are not singleton/multiton (could they be?) Of course the fix is something like: class A def a(y) @a_b ||= lambda { |x| x + y } 10.times { |i| print @a_b(i) } end end But true inner methods would be the bomb for these use cases (IMHO). T.