Random Tip: Fun with Splat Operators!
Normally when you see the “*” character, you associate it with the multiplication function. However, if you see it before a variable name, it can have interesting purposes depending on the state of that variable.
If you find it before an argument collection variable in a method:
then it takes in all arguments into an array, so that if you call on the method:
then args would be a local variable within that method equalling [1, 2, 3, 4, 5].
You can separate out multiple arguments accepted for the method and have the splat operator absorb any arguments that are left over after the other arguments have been assigned, if any (it wold be an empty array if there are not enough arguments passed for it to take in any after the other arguments are collected).
Here’s the (slightly) tricky part. The splat operator can take in all of the arguments at the end, the beginning, or even from the middle! Here are three examples.
method (1, 2, 3, 4, 5) #=> [1, 2, [3, 4, 5]]
_______________________________________________________________________
method (1, 2, 3, 4, 5) #=> [[1, 2, 3], 4, 5]
_______________________________________________________________________
method (1, 2, 3, 4, 5) #=> [1, [2, 3, 4], 5]
_______________________________________________________________________
The double splat “**” is similar, except it converts arguments passed in as key value pairs into a hash and can only be at the end of the argument collection for a method:
method (1, 2, a: 3, b: 4, c: 5) #=> [1, 2, {3, 4, 5}]
Once a key value pair is passed, then it only expects the rest of the arguments passed to be key value pairs and raises an error message if this format is not adhered to.
Splat operators can also be used in deconstructing their respective arrays and hashes into their individual elements/key-value pair. So, if you had an array:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
method(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
and the same for the double splat hash
nums = {a: 1, b: 2, c: 3}
method(nums) #=> method(a: 1, b: 2, c: 3)
which probably wouldn’t work very well unless you had a double splat operator to catch those key value pairs!
You can also use the splat operator to do some quick variable assignments. Just like with :
a, b = 1, 2 #=> a = 1, b = 2
a, *b, c = 1, 2, 3, 4, 5 #=> a = 1, b = [2, 3, 4], c = 5
The last thing I will mention about the splat operator is that you can use it to coerce into array format things that normally can’t be converted into an array:
a = “Hello”.to_a #=> NoMethodError: undefined method `to_a' for "Hello":String
b = *”Hello” #=> [”Hello”]