On Fri, Aug 29, 2008 at 12:51 PM, Hunt Jon <jona.hunt777 / gmail.com> wrote:
> I'm new to Ruby with PHP background.
>
> * Is there any super easy explanation or tutorial for proc and lamda?
> * Do I need experience with Lisp or Smalltalk?
>
> Proc and lambda are most fun part in ruby, people say. But, I feel I'm
> dumb. I read the Pickaxe book, but couldn't fully understand the
> concept. I don't have to be able to use them soon, but I at least need
> to comprehend them.

The easiest way for me to understand those are to think of them
as anonymous methods, that can be stored in variables and called
later on:

irb(main):001:0> l = lambda {|x| puts x}
=> #<Proc:0xb7c1c8cc@(irb):1>
irb(main):002:0> l.call("hello")
hello
=> nil

An important characteristic is that they are closures. This means that
they "trap" the scope in which they are defined, and have access to that
scope when they are called, even though the call can be made in a different
scope. This is better explained with an example:

irb(main):003:0> class Test
irb(main):004:1> def execute (l)
irb(main):005:2> l.call("test")
irb(main):006:2> end
irb(main):007:1> end
=> nil
irb(main):008:0> x = "a variable"
=> "a variable"
irb(main):009:0> l = lambda {|var| puts "#{var} - #{x}"}
=> #<Proc:0xb7bf74dc@(irb):9>
irb(main):010:0> Test.new.execute(l)
test - a variable

As you can see, the lamdba block is executed in the scope of the
method execute of class Test, where the variable x is not in scope.
But, the block has access to x, cause it's a closure.

Hope I didn't mess the explanation...

There are some subtle differences between Proc, lambda and proc that
I'm not too sure about, so I'll leave that explanation to others.

Jesus.