What does this mean in Ruby language?
Asked Answered
A

3

5

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!

Astto answered 1/9, 2010 at 13:43 Comment(0)
F
16

head, *tail = a means to assign the first element of the array a to head, and assign the rest of the elements to tail.

*, 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:

head, tail = [1, 2, 3, 4, 5]
p head # => 1
p tail # => 2

But when you add the splat to tail it means "Everything that didn't get assigned to the previous variables (head), assign to tail."

Flaunty answered 1/9, 2010 at 13:49 Comment(3)
nice answer! :) but you really should change your profile pic, you look like an overly groomed poodle ;) heheCharente
Haha. I haven't got that one before. I'll take it under advisement. :)Flaunty
@banister: His current pic (maybe not the same one used back then) makes him look like Justin Bieber!Hexapod
G
8

First, it is a parallel assignment. In ruby you can write

a,b = 1,2

and a will be 1 and b will be 2. You can also use

a,b = b,a

to swap values (without the typical temp-variable needed in other languages).

The star * is the pack/unpack operator. Writing

a,b = [1,2,3]

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:

a,*b = [1,2,3]
Goldston answered 1/9, 2010 at 13:57 Comment(0)
C
0

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 variables head and tail.

This mechanism is usually referred (at least in Erlang) as pattern matching.

Chas answered 1/9, 2010 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.