rubyparallel-assignment

Why does parallel assignment of a single empty array assign multiple nils?


I want to assign an empty array to multiple variables. Here is what I'm doing:

irb(main):015:0> a, b, c = []
=> []
irb(main):016:0> a
=> nil
irb(main):017:0> b
=> nil
irb(main):018:0> c
=> nil

It gives me nil. I wonder why? But if I did this:

irb(main):019:0> a, b, c = [], [], []
=> [[], [], []]
irb(main):020:0> a
=> []
irb(main):021:0> b
=> []
irb(main):022:0> c
=> []

then it works as I expect, but it's a little bit longer than the first one. What's wrong with the first example?


Solution

  • I believe this example will help you understand the problem:

    [1] pry(main)> a, b, c = [1,2]
    => [1, 2]
    [2] pry(main)> a
    => 1
    [3] pry(main)> b
    => 2
    [4] pry(main)> c
    => nil
    

    Now back to your problem, you are trying to assign the elements in an empty array to variables, as a result, the three variables all get nil value.