Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this mean in Ruby language?

Tags:

ruby

splat

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!

like image 975
Just a learner Avatar asked Sep 01 '10 13:09

Just a learner


1 Answers

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."

like image 151
Jordan Running Avatar answered Oct 01 '22 09:10

Jordan Running