...">

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.

+4
source share
3 answers

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)
+3
source

, . :

> *foo = 1
> foo
 => [1]

, *second letters[1..-1]. letters[1], "b" second.

, - , .

splat operator.

+2

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]
+2
source

All Articles