2

Say I have an array, [1,2,3,4] and want to use parallel assignment to assign a to 1 and b to 3. I figured I could do something like:

a, _, b, _ = [1,2,3,4] 

or even omit the last _ and it will work but Ruby will produce warnings for this for unused variables. Is there some other way to do this? Is this way of using underscores recommended?

2 Answers 2

3

There should not be any warning about unused variables, provided of course that you actually use a and b somewhere. Using _ in this way is recommended and idiomatic, and even officially supported by the interpreter in that it actually does not generate warnings for unused variables if the name of the variable is _ or starts with _.

Sign up to request clarification or add additional context in comments.

Comments

2

The warning is about unused variables a and b, not about _. An alternative :

a, b = [1,2,3,4].values_at(0,2)

1 Comment

Using values_at is my preferred way of doing/seeing it. It's a lot easier to figure out what elements are being retrieved and assigned. Using _ works but we're left having to figure out which variables are assigned which elements when reading it.

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.