What is the standalone splat operator (*) used for

2020-02-11 09:12发布

I just came across this example where the splat operator is used by itself in a method definition:

def print_pair(a,b,*)
  puts "#{a} and #{b}"
end

print_pair(1,2,3,:cake,7)
#=> 1 and 2

It is clear what and why you would use it in a context like so:

def arguments_and_opts(*args, opts)
  puts "arguments: #{args} options: #{opts}"
end

arguments_and_opts(1,2,3, a: 5)
#=> arguments: [1, 2, 3] options: {:a=>5}

But why and how would you use it in the first example? Since it is defined in the Ruby specs there must be a usecase for it?

标签: ruby splat
2条回答
家丑人穷心不美
2楼-- · 2020-02-11 09:30

In a parameter list, *args means "gobble up all the remaining arguments in an array and bind them to the parameter named args". * means "gobble up all the remaining arguments and bind them to nothing", or put more simply "ignore all remaining arguments".

And that's exactly when you would use this: when you want to ignore all the remaining arguments. Either because you don't care about them, or because you don't care about them (but someone else might):

def foo(*)
  # do something
  super
end

Remember: super without an argument list passes the arguments along unmodified. So, even though this override of foo ignored the arguments, they are still available to the superclass's implementations of the method; yet, the definition makes it clear that this implementation doesn't care.

查看更多
疯言疯语
3楼-- · 2020-02-11 09:38

It is used emphasise, that method requires two arguments, but you can pass any amount (rest will be ignored).

You can check method's parameters with Method#parameters:

method(:print_pair).parameters
#=> [[:req, :a], [:req, :b], [:rest]]
查看更多
登录 后发表回答