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/.