Reputation: 75
a = [1, 2, 3, 4]
b, c = 99, *a → b == 99, c == 1
b, *c = 99, *a → b == 99, c == [1, 2, 3, 4]
Can someone please throughly explained why in Ruby the asterisk makes the code return what it returns? I understand that the if an lvalue has an asterisk, it assigns rvalues to that lvalues. However, why does '*a' make 'c' return only the '1' value in the array and why does '*a' and '*c' cancel each other out?
Upvotes: 0
Views: 52
Reputation: 66263
In both cases, 99, *a
on the right-hand side expands into the array [99, 1, 2, 3, 4]
In
b, c = 99, *a
b
and c
become the first two values of the array, with the rest of the array discarded.
In
b, *c = 99, *a
b
becomes the first value from the array and c
is assigned the rest (because of the splat on the left-hand side).
The 99, *a
on the right-hand side is an example of where the square brackets around an array are optional in an assignment.
A simpler example:
a = 1, 2, 3 → a == [1, 2, 3]
Or a more explicit version of your example:
example = [99, *a] → example == [99, 1, 2, 3, 4]
Upvotes: 4