In article <_Ccdd.16031$nj.9139 / newssvr13.news.prodigy.com>, Sam Sungshik Kong <ssk / chol.nospam.net> wrote: > ><snip> >def makeCounter > var = 0 > lambda do > var +=1 > end >end > >c1 = makeCounter >c1.call >c1.call >c1.call > >c2 = makeCounter > >puts "c1 = #{c1.call}, c2 = #{c2.call}" ></snip> In this case makeCounter returns a lambda (an anonymous function, which is also known as a closure). Notice that closures can carry around information from the scope they are defined in - so var is first defined outside of the lambda 'block', but even when this closure is returned outside of that scope it still knows about var. The part between the do ... end in the method above is that block. > > >Here is what the above page(http://martinfowler.com/bliki/Closures.html) >says... > ><snip> >Closures have been around for a long time. I ran into them properly for the >first time in Smalltalk where they're called Blocks. Lisp uses them heavily. >They're also present in the Ruby scripting language - and are a major reason >why many rubyists like using Ruby for scripting. > >Essentially a closure is a block of code that can be passed as an argument >to a function call. > >... > >In a language that has Closures, in this case Ruby, I'd write this. > >def managers(emps) > return emps.select {|e| e.isManager} >end ></snip> > >This is just a block, right? This -> {|e| e.isManager} is the block. >Is it also a closure? I guess I would kind of think of it as the definition or blueprint for the closure - Is it really a closure before it gets turned into a proc or lamda? The emps object responds to a select method call. The definition of select might look like (2 alternatives): #using yield: def select #develop some variable var yield var end #alternatively, it could be defined by #explicitly requiring a block to be passed in: def select &b #develop some variable var b.call(var) end The second alternative is probably more instructive for our purposes. The '&' before the 'b' indicates that the select method takes a block as a parameter - as the block is passed in it is transformed into a Proc object and it become a closure (at least that's the way I think of it). However, the block will still carry around the context (variables defined in the scope where the block was defined) where it was defined. Phil