On Thu, Feb 14, 2013 at 9:31 PM, RKA <[email protected]> wrote:
> Lambda functions are used when you want to call a function that doesn't
> necessarily need a name.

I would put it differently: lambdas are used when you need to use a
function as an object which can be referenced and passed around.

> For example, the each method of the array object
> iterates through all the items in the array and if you want to execute the
> same method over and over again with a different argument you can use a
> lambda function, instead of having to define a function first.

That is probably not such a good example because #each already uses a
different mechanism by using the block passed to the call.  Typically
one would do

array.each do |x|
  # logic 1
end

array.each do |x|
  # logic 2
end

lambdas are really most useful if you store them somewhere for later
execution.  This example is not brilliant but I hope it demonstrates
the point:

irb(main):001:0> Calculator = Struct.new :function do
irb(main):002:1* def apply(x, y) function[x, y] end
irb(main):003:1> end
=> Calculator
irb(main):004:0> c = Calculator.new lambda {|a,b| a*b}
=> #<struct Calculator function=#<Proc:0x8003b698@(irb):4 (lambda)>>
irb(main):005:0> c.apply(2, 4)
=> 8
irb(main):006:0> c.apply(4, -3)
=> -12

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- 
[email protected] | 
https://groups.google.com/d/forum/ruby-talk-google?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"ruby-talk-google" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to