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?
A parameter with the splat operator converts the arguments to an array within a method. The arguments are passed in the same order in which they are specified when a method is called. A method can't have two parameters with splat operator.
The splat operater, placed before a parameter in a method signature (as above) tells the method to accept an unlimited number of arguments as an array.
In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).
The * is the splat operator. It expands an Array into a list of arguments, in this case a list of arguments to the Hash.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With