tags:

views:

199

answers:

2

This code works as expected (does nothing, even doesn't produce warning/errors):

l = lambda {|i|}
l.call(1)

This code produces warning (warning: multiple values for a block parameter (0 for 1)):

l = lambda {|i|}
l.call

And this code fails with error (ArgumentError: wrong number of arguments (0 for 2)):

l = lambda {|i, y|}
l.call

I thought that lambda requires all argument to be passed.

And from the second example I see that it isn't. Why does it work when only one argument is given, and works as expected (fails with error) with more than one argument?

PS: ruby 1.8.6 (2008-08-11 patchlevel 287) [universal-darwin9.0]

UPDATE: I've checked these samples with ruby 1.9.1p376. And it works as expected - the second example also produces an error. Looks like this is a feature of 1.8 version (or <=1.8)

+2  A: 

This script will teach you everything you need to know about closures in Ruby.

# So, what's the final verdict on those 7 closure-like entities?          
#
#                                                     "return" returns from closure
#                                    True closure?    or declaring context...?         Arity check?
#                                    ---------------  -----------------------------    -------------------
# 1. block (called with yield)       N                declaring                        no
# 2. block (&b => f(&b) => yield)    N                declaring                        no
# 3. block (&b => b.call)            Y except return  declaring                        warn on too few
# 4. Proc.new                        Y except return  declaring                        warn on too few
# 5. proc                                    <<< alias for lambda in 1.8, Proc.new in 1.9 >>>
# 6. lambda                          Y                closure                          yes, except arity 1
# 7. method                          Y                closure                          yes
Trevoke
Sorry, but I can't find an answer there. Could you please point?
Andrew Dashin
Added a pointer :)
Trevoke
Thank you! But anyway, it is still unclear why such behaviour exists (to be correct - existed)
Andrew Dashin
+1  A: 

Lambdas are weird like that, their behavior is different when you have less than two arguments. Check this article for more information.

Firas Assaad