Search code examples
rubyruby-hash

How to push a value to an array value in a hash


I'm trying to set different arrays as the values of a hash using a range, then push a value into one of the arrays. I want this outcome:

hash[0] << 3 
hash #=> {0=>[3], 1=>[], 2=>[], 3=>[]}

I did this:

hash = Hash[(0..9).to_a.product([Array.new(0)])]
#=> {0=>[], 1=>[], 2=>[], 3=>[], 4=>[], 5=>[], 6=>[], 7=>[], 8=>[], 9=>[], 10=>[]}
hash[0] << 3 #=> [3]
hash #=> {0=>[3], 1=>[3], 2=>[3], 3=>[3], 4=>[3], 5=>[3], 6=>[3], 7=>[3], 8=>[3], 9=>[3], 10=>[3]}

I assume the reason I get the output is because all my keys are referencing the same array instead of different arrays.

How could I get the expected outcome?


Solution

  • You have to assign a new array to each key. There are many ways of doing this. Here's a couple:

    hash = (0..9).each_with_object({}) { |i, result| result[i] = [] }
    hash = (0..9).map{|i| [i, []]}.to_h