Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

splat

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?

like image 847
Severin Avatar asked Feb 10 '17 11:02

Severin


People also ask

What does the splat operator do in Ruby?

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.

What is use of 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.

What is * args in Ruby?

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).

What does Asterisk do in Ruby?

The * is the splat operator. It expands an Array into a list of arguments, in this case a list of arguments to the Hash.


1 Answers

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.

like image 108
Jörg W Mittag Avatar answered Sep 24 '22 14:09

Jörg W Mittag