Search code examples
rubynullvariable-assignmentassignassignment-operator

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']

Solution

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

    You could also replace *_ with just *.

    Yes, _ is a perfectly valid local variable.

    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. Some prefer using a variable name that begins with an underscore for values that won't be used:

    _key, value = [1, 2]
    

    If you assign fewer variables that there are elements of the array, the elements at the end of the array are discarded. For example,

    a, b = [1, 2, 3]
    a #=> 1
    b #=> 2