Why do Ruby procs/blocks with splat arguments behave differently than methods and lambdas? -
why ruby (2.0) procs/blocks splat arguments behave differently methods , lambdas?
def foo (ids, *args) p ids end foo([1,2,3]) # => [1, 2, 3] bar = lambda |ids, *args| p ids end bar.call([1,2,3]) # => [1, 2, 3] baz = proc |ids, *args| p ids end baz.call([1,2,3]) # => 1 def qux (ids, *args) yield ids, *args end qux([1,2,3]) { |ids, *args| p ids } # => 1
here's confirmation of behavior, without explanation: http://makandracards.com/makandra/20641-careful-when-calling-a-ruby-block-with-an-array
there 2 types of proc
objects: lambda
handles argument list in same way normal method, , proc
use "tricks" (proc#lambda?). proc
splat array if it's argument, ignore arguments, assign nil
missing ones. can partially mimic proc
behavior lambda
using destructuring:
->((x, y)) { [x, y] }[1] #=> [1, nil] ->((x, y)) { [x, y] }[[1, 2]] #=> [1, 2] ->((x, y)) { [x, y] }[[1, 2, 3]] #=> [1, 2] ->((x, y)) { [x, y] }[1, 2] #=> argumenterror
Comments
Post a Comment