Ruby single splat / double splat arguments
Splat operator or start (*) arguments in Ruby define they way they are received to a variable. Single splat operator can be used to receive arguments as an array to a variable or destructure an array into arguments. Double splat operator can be used to destructure a hash.
Single Splat (*) Operator
Single splat operator collects all the arguments in a variable as an array. It can be used to destructure an array values into variable(s).
Single splat operator in method definition
Let’s take an example.
We have defined a method post_keywords
that receives
arguments in a variable named keywords
.
The first line in the code prints class name
of the variable keywords
.
Second line in the code prints values
of keywords.
Let’s call the method defined above.
The result of method call above, it prints out values as given below.
As we can see, single splat operator does following things.
- Receive arguments (values) as an Array to a variable
- Individual arguments can be accessed from array element
Single splat operator with multiple arguments
Single splat operator can be used with multiple arguments in ruby.
This defined a method post_keywords
,
that accepts first argument as name of the site
and
second argument as keywords.
Now, we can call the method as given below.
It will output as given below.
- We defined a method to receive
site_name
as a first argument - Rest of the arguments are gobbled up by splat operator in
keywords
variable
Single splat operator to destructure an array
Single splat operator can be used to destructure an array as given below. Let’s say, we have an array with first value as site name and rest of the arguments as site tags.
Now, we can use single splat operator to destructure as given below.
We can verify values to see that,
site_name
has valueRuby in Rails
tags
has value["Ruby", "Rails"]
Double Splat (**) Operator
Double splat operator can be used to destructure a hash.
Let’s say we have a hash with keywords
key
with value of keywords for the post.
Another hash with site_name
key as given below.
And we need to prepare a hash having
key values from both hashes keyword_options
and
site_options
.
It can be created with code given below.
all_options
will have values as given below.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox