O.Powell
O.Powell

Reputation: 172

How exactly does the ruby splat operator get the first and rest of an Array during multiple assignment?

In ruby its possible to combine multiple assignment with the splat operator in order to simulate first and rest (or head and tail) found in functional languages.

first, *rest = [1,2,3,4]  
first # output: 1
rest # output: [2,3,4]

How is the splat operator achieving this?

Upvotes: 2

Views: 495

Answers (1)

sawa
sawa

Reputation: 168269

You can have at most one splat operator in multiple assignment, and the splat operator will adjust the length of the array to exhaustively match what is on the right side. In other words:

1) When the number of variables on the left side is more than the length of the array on the right side, then, the variable with the splat will be assigned an empty array:

*a = []
# => a == []

*a, b = [1]
# => a == [], b == 1

a, *b = [1]
# => a == 1, b == []

*a, b, c = [1, 2]
# => a == [], b == 1, c == 2

a, *b, c = [1, 2]
# => a == 1, b == [], c == 2

a, b, *c = [1, 2]
# => a == 1, b == 2, c == []

...

2) Otherwise, the variable with the splat will expand to be filled up with the rest of the elements from the right side:

*a = [1, 2]
# => a == [1, 2]

*a, b = [1, 2, 3]
# => a == [1, 2], b == 3

a, *b = [1, 2, 3]
# => a == 1, b == [2, 3]

*a, b, c = [1, 2, 3, 4]
# => a == [1, 2], b == 3, c == 4

a, *b, c = [1, 2, 3, 4]
# => a == 1, b == [2, 3], c == 4

a, b, *c = [1, 2, 3, 4]
# => a == 1, b == 2, c == [3, 4]

....

Upvotes: 6

Related Questions