Reputation: 8424
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?
Upvotes: 2
Views: 164
Reputation: 369458
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 _
.
Upvotes: 3
Reputation: 80065
The warning is about unused variables a
and b
, not about _
. An alternative :
a, b = [1,2,3,4].values_at(0,2)
Upvotes: 2