Why do Ruby procs/blocks with splat arguments behave differently than methods and lambdas?

后端 未结 2 1900
难免孤独
难免孤独 2021-01-02 17:17

Why do Ruby (2.0) procs/blocks with splat arguments behave differently than methods and lambdas?

def foo (ids, *args)
  p ids
end
foo([1,2,3]) # => [1, 2,         


        
2条回答
  •  旧巷少年郎
    2021-01-02 17:25

    Just encountered a similar issue!

    Anyways, my main takeaways:

    1. The splat operator works for array assignment in a predictable manner

    2. Procs effectively assign arguments to input (see disclaimer below)

    This leads to strange behavior, i.e. the example above:

    baz = proc do |ids, *args|
      p ids
    end
    baz.call([1,2,3]) # => 1
    

    So what's happening? [1,2,3] gets passed to baz, which then assigns the array to its arguments

    ids, *args = [1,2,3]
    ids = 1
    args = [2,3]
    

    When run, the block only inspects ids, which is 1. In fact, if you insert p args into the block, you will find that it is indeed [2,3]. Certainly not the result one would expect from a method (or lambda).

    Disclaimer: I can't say for sure if Procs simply assign their arguments to input under the hood. But it does seem to match their behavior of not enforcing the correct number of arguments. In fact, if you give a Proc too many arguments, it ignores the extras. Too few, and it passes in nils. Exactly like variable assignment.

提交回复
热议问题