letters = ["a", "b", "c", "d", "e"]
first, *second = letters
first # => "a"
second # => "["b", "c", "d", "e"]
I understand what this produces, but can't get my head around this. Is this basically Ruby magic? Can't think of any other programming language that would support this type of assignment with the splat operator.
This is quite a common thing in functional languages, so Ruby is not alone. You have a list of items and want it separated in a head
and a tail
, so you can perform an operation on the first element of the list.
This also works:
letters = ["a", "b", "c", "d", "e"]
first, *middle, last = letters
In a functional language like Clojure, you would see something like:
(first '(1 2 3)) => 1
(rest '(1 2 3)) => (2 3)
This is a very interesting thing here is described in great detail all the "magical properties"
for example
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With