x = lambda { return "ar har har har" }
If you're not new to Ruby, you've probably heard of procs. These are very similar to lambdas with very subtle, yet significant, differences. The most notable difference between a proc and a lambda is that returning from a proc will actually return from the method its defined within. Example:
def a_meth
proc = Proc.new{ return "blah" }
proc.call
return "not reached"
end
def a_new_meth
lam = lambda{ return "yeeee hah" }
lam.call
return "not the lambda"
end
The output is "not the lambda"; that is, unlike proc.call, lam.call does not force an immediate exit from the enclosing block.
> x = lambda { |x, y| puts x + y }
and call it like so,
> x.call(1, 2, 3)
you will get a "wrong number of arguments" error.
p = Proc.new{|x,y| puts x + y}
p.call(1,2,3)
That'll return the expected number 3, which is the sum of the first two arguments passed into the function
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)