有没有没有 (*)splat 参数的方法来在 Ruby 中传递多个参数?

Is there a way without a (*)splat argument to pass multiple arguments in Ruby?

我需要编写一个方法,该方法采用未知数量的参数(因此是 *splat)但它通过了 yields_with_args 规范。

代码:

def eval_block(*args, &block)
    raise "NO BLOCK GIVEN!" if block.nil?
       block.call(args)
end

rspec:

it "passes the arguments into the block" do
      expect do |block|
        eval_block(1, 2, 3, &block)
      end.to yield_with_args(1, 2, 3)
    end
end

它有效,但它产生 *splat 创建的数组:[1,2,3]1,2,3,因此不通过 rspec。还有另一种方法可以通过Ruby中的方法传递多个参数吗?

替换

block.call(args)

block.call(*args)

Splat 有两个功能:定义时收集参数到数组,调用时将数组分发到参数。两者是逆操作:如果你希望透明操作(三个参数进,三个参数出),你应该分发你收集的东西。