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
The first line in the code prints class name
of the variable
Second line in the code prints values
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
that accepts first argument as name of the site
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_nameas a first argument
- Rest of the arguments are gobbled up by splat operator in
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,
Ruby in Rails
Double Splat (**) Operator
Double splat operator can be used to destructure a hash.
Let’s say we have a hash with
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
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