daremkd
daremkd

Reputation: 8424

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

Upvotes: 5

Views: 803

Answers (3)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

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]

Upvotes: 3

zwippie
zwippie

Reputation: 15515

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)

Upvotes: 3

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

I think it basically creates an array. Look at the following example:

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

So here *second will create an array and extract all elements from letters[1..-1]. Otherwise it would just assign letters[1], which is "b" to the second variable.

I'm sure someone will come up with a better explanation, but the basic idea is here.

More information about the splat operator.

Upvotes: 2

Related Questions