Hi --

On Thu, 8 Oct 2009, 7stud -- wrote:

> How is it that both the following calls to test() work:
>
> def test
>  yield [10, "red"]
> end
>
> test {|x| p x}
> puts
>
> test do |x, y|
>  p x
>  puts "--"
>  p y
> end
>
> --output:--
> [10, "red"]
>
> 10
> --
> "red"
>
>
> After all, this doesn't work:
>
> def test(x, y)
>  p x
>  p y
> end
>
> test([10, "red"])
>
> --output:--
> `test': wrong number of arguments (1 for 2) (ArgumentError)
>        from r1test.rb:19

Lambda-flavored Proc objects are fussier about arity than
non-lambda-flavored ones. For example:

   def test
     yield(1)
   end

   test(&proc {|x,y| puts "Will get here in 1.9.1"})
   test(&lambda {|x,y| puts "Won't get here in 1.9.1"})

Output:

   Will get here in 1.9.1
   -:2:in `test': wrong number of arguments (1 for 2) (ArgumentError)

So the lambda is more method-like in this particular respect than the
non-lambda Proc (since methods, likewise, care about arity).


David

-- 
The          Ruby training with D. Black, G. Brown, J.McAnally
Compleat     Jan 22-23, 2010, Tampa, FL
Rubyist      http://www.thecompleatrubyist.com

David A. Black/Ruby Power and Light, LLC (http://www.rubypal.com)