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

牧云@^-^@ 提交于 2019-11-29 08:14:48

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.

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