0
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?

2
  • 1
    You are asking for an explanation of a language construct, something that is covered in basic texts and articles in far greater detail and thoroughness than you could expect to get here. You just need to know what to look for, which is not always obvious to those new to the language. Try Googling, "Ruby parallel assignment destructuring splat". You will get several good hits, including this excellent article by Adam Sanderson... Commented Nov 18, 2018 at 17:46
  • 1
    ... Also, the section on "Assignment" in The Ruby Programming Language, by Matsumoto and Flanagan, is required reading. See especially the subsection "Parallel Assignment". Commented Nov 18, 2018 at 17:46

1 Answer 1

4

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.