InQusitive InQusitive - 12 days ago 7
Ruby Question

Why doesn't a proc care about the number of arguments?

def method1(&proc)
proc.call(1,2,3)
end

method1{ |x,y,z,a| puts a}


Doesn't throw any error and outputs
nil
.

Why doesn't it check for the arguments? What's the logic behind it?

Answer

Proc's do no care about validating the right number of arguments but lambda's do...

def method1(&proc)
  proc.call(1,2,3)
end

method1 { |x,y,z,a| puts a}
method1 lambda { |x,y,z,a| puts a }

Results in:

lambda.rb:1:in `method1': wrong number of arguments (given 1, expected 0) (ArgumentError)
    from lambda.rb:6:in `<main>'

From the ruby docs:

For procs created using lambda or ->() an error is generated if the wrong number of parameters are passed to a Proc with multiple parameters. For procs created using Proc.new or Kernel.proc, extra parameters are silently discarded.

Comments