Run the following code,
a = [1, 2, 3, 4, 5]
head, *tail = a
p head
p tail
You will get the result
1
[2, 3, 4, 5]
Who can help me to explain the statement head,*tail = a
, Thanks!
Run the following code,
a = [1, 2, 3, 4, 5]
head, *tail = a
p head
p tail
You will get the result
1
[2, 3, 4, 5]
Who can help me to explain the statement head,*tail = a
, Thanks!
I don't know Ruby at all, but my guess is that the statement is splitting the list
a
into a head (first element) and the rest (another list), assigning the new values to the variableshead
andtail
.This mechanism is usually referred (at least in Erlang) as pattern matching.
First, it is a parallel assignment. In ruby you can write
and a will be 1 and b will be 2. You can also use
to swap values (without the typical temp-variable needed in other languages).
The star * is the pack/unpack operator. Writing
would assign 1 to a and 2 to b. By using the star, the values 2,3 are packed into an array and assigned to b:
head, *tail = a
means to assign the first element of the arraya
tohead
, and assign the rest of the elements totail
.*
, sometimes called the "splat operator," does a number of things with arrays. When it's on the left side of an assignment operator (=
), as in your example, it just means "take everything left over."If you omitted the splat in that code, it would do this instead:
But when you add the splat to
tail
it means "Everything that didn't get assigned to the previous variables (head
), assign totail
."