How does this parallel assignment with the splat operator work in Ruby?
letters = ["a", "b", "c", "d", "e"]
first, *second = letters
first # => "a"
second # => "["b", "c", "d", "e"]
I understand that this produces, but I canβt think about it. Is it mostly ruby ββmagic? It is impossible to imagine any other programming language that supports this type of assignment using the splat operator.
This is quite common in functional languages, so Ruby is not alone. You have a list of items and want them to be divided by headand tail, so you can perform the operation on the first item in the list.
This also works:
letters = ["a", "b", "c", "d", "e"]
first, *middle, last = letters
In a functional language such as Clojure, you will see something like:
(first '(1 2 3)) => 1
(rest '(1 2 3)) => (2 3)
This is a very interesting thing. All magic properties are described in detail here.
eg
a, *b, c = [1, 2, 3, 4, 5]
a # => 1
b # => [2, 3, 4]
c # => 5
a, (b, c) = [2,[2,[6,7]]]
a
=> 2
b
=> 2
c
=> [6, 7]