Seventh article in the Prepare for a Ruby job interview series. In this article, we’re going to talk about *, A.K.A the Splat operator, which is a great tool as we’ll see.
The splat operator is a very nice trick that let you do many things. Let’s see what!
1. When used in a function arguments, it will collect all the remaining arguments in an array.
def print_stuff(stuff, *arguments)
p stuff
arguments.each { |arg| p arg}
end
print_stuff('yes', 'no', 'maybe', 'what?')
# => "yes"
# => "no"
# => "maybe"
# => "what?"
2. Convert an array to arguments :
def add(a, b, c)
p a + b + c
end
add(*[1, 2, 3])
# => 6
3. Create an array
stuff = *'Test'
p stuff
# => ["Test"]
4. Convert a hash to an array :
stuff = *{ a: 1, b: 2, c:3 }
p stuff
# => [[:a, 1], [:b, 2], [:c, 3]]
5. Assign multiple variables :
# You can also put it on the b variable
*a, b = [1, 2, 3, 4, 5]
p a
p b
# => [1, 2, 3, 4]
# => 5
6. Flatten an array
a = [1, 2, 3, 4, 5]
b = [*a, 6, 7]
p b
# => [1, 2, 3, 4, 5, 6, 7]
Checkout the next article about some cool Ruby tricks.