What is the standalone splat operator (*) used for in Ruby?

谁都会走 提交于 2019-12-03 18:05:24

问题


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?


回答1:


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.




回答2:


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]]


来源:https://stackoverflow.com/questions/42158005/what-is-the-standalone-splat-operator-used-for-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!