Careful when calling a Ruby block with an array

Posted . Visible to the public.

When a Ruby block or proc takes multiple parameters, and you call it with an Array, Ruby will unexpectedly splat the array elements:

block = proc { |a, b| "a=#{a}, b=#{b}" }
block.call(1, 2)   # "a=1, b=2"
block.call([1, 2]) # "a=1, b=2"

Note that lambdas behave as expected:

block = lambda { |a, b| "a=#{a}, b=#{b}" }
block.call(1, 2)   # "a=1, b=2"
block.call([1, 2]) # ArgumentError: wrong number of arguments (1 for 2)
Profile picture of Henning Koch
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2013-12-17 13:36)