Ulysse BN Ulysse BN - 1 month ago 6
Ruby Question

How can I assign a value to a void variable using ruby’s multiple assignment?

I would like to use multiple assignment but I don’t care about some part of the values I have in input. So is there a way to assign something to a void variable (aka

/dev/null
from bash) ? something like
nil = 'I wont be used'
. I have a more specific example of what I want to achieve below.

My input is :

['no','foo','nop','not at all','bar']


And I assign it this way :

i,foo,dont,care,bar = ['no','foo','nop','not at all','bar']
#or with a splat :
dont,foo,*care,bar = ['no','foo','nop','not at all','bar']


What I would like to do is something like this :

nil,foo,*nil,bar = ['no','foo','nop','not at all','bar']

Answer
_, foo, *_, bar = ['no','foo','nop','not at all','bar']
foo #=> "foo"
bar #=> "bar"
_ #=> ["nop", "not at all"]

Yes, _ is a perfectly valid local variable. It differs from any other local variable, however, in that can appear more than once on the left side of the expression without raising an exception.

Of course, you don't have to use _ for the values you won't be using. For example, you could write

cat, foo, *dog, bar = ['no','foo','nop','not at all','bar']

Using _ may reduce the chance of errors, but mainly it's for telling the reader that you are not going to use that value.

In any event, you have to assign each element of the array to a local variable and/or a (single) contiguous group of elements to a splatted variable.