Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!feeder.news-service.com!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!talisker.lacave.net!lacave.net!not-for-mail From: Brian Candler Newsgroups: comp.lang.ruby Subject: Re: anonymous closures with Proc,new, lambda and -> Date: Tue, 19 Apr 2011 03:15:59 -0500 Organization: Service de news de lacave.net Lines: 36 Message-ID: <52198c724199b47f9d59c43592238d37@ruby-forum.com> References: NNTP-Posting-Host: bristol.highgroove.com Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Trace: talisker.lacave.net 1303201004 85452 65.111.164.187 (19 Apr 2011 08:16:44 GMT) X-Complaints-To: abuse@lacave.net NNTP-Posting-Date: Tue, 19 Apr 2011 08:16:44 +0000 (UTC) In-Reply-To: X-Received-From: This message has been automatically forwarded from the ruby-talk mailing list by a gateway at comp.lang.ruby. If it is SPAM, it did not originate at comp.lang.ruby. Please report the original sender, and not us. Thanks! For more details about this gateway, please visit: http://blog.grayproductions.net/categories/the_gateway X-Mail-Count: 381830 X-Ml-Name: ruby-talk X-Rubymirror: Yes X-Ruby-Talk: <52198c724199b47f9d59c43592238d37@ruby-forum.com> Xref: x330-a1.tempe.blueboxinc.net comp.lang.ruby:3150 Brian Candler wrote in post #993704: > And you can do the same without explicitly binding 'counter_maker' > either: > > c = lambda { |init| lambda { init += 1 } }.call(200) > c.call # 201 > c.call # 202 Which of course simplifies to: c = lambda { init = 200; lambda { init += 1 } }.call c.call # 201 c.call # 202 The outer lambda here is just to ensure that 'init' is in its own scope, so if you run this code multiple times, each lambda returned has an independent instance of 'init' Note: this only works as long as 'init' hasn't already been seen outside; if it has, all the lambdas will bind to the same 'init'. In ruby 1.9 there's a way to force it to be local: c = lambda { |;init| init = 200; ...etc... }.call But in that case the original code would be shorter: c = lambda { |init| ...etc... }.call(200) This does the same in 1.9 (because block parameters are always local), but in 1.8 it would still bind to the outside 'init' variable if one exists. -- Posted via http://www.ruby-forum.com/.