Adding a hash that has an array in Ruby and adding to that array

82 views Asked by At

Hello all I'm new and I've been searching and can't find a clear answer to this question, I'm hoping this summarizes it:

a = {:a1 => "a1", :b1 => [] }

how would I add :c1 to the a hash and make it another hash, leading to an array, and add values to that array? I would like the return of the a hash to resemble:

=> {:a1 => "a1", :b1 => [], :c1 => {c2 => [0, 1]}
2

There are 2 answers

1
spickermann On

In multiple steps:

a = { :a1 => "a1", :b1 => [] }
a[:c1] = {}
a[:c1][:c2] = []
a[:c1][:c2] << 0
a[:c1][:c2] << 1

a #=> { :a1 => "a1", :b1 => [], :c1 => { :c2 => [0, 1] } }

Or in one step:

a = { :a1 => "a1", :b1 => [] }
a[:c1] = { c2: [0, 1] }

a #=> { :a1 => "a1", :b1 => [], :c1 => { :c2 => [0, 1] } }
1
Todd A. Jacobs On

Merging Hashes

One option among others is to use Hash#merge!. For example:

a = {:a1=>"a1", :b1=>[]}
a.merge!({:c1=>{:c2=>[0, 1]}})
#=> {:a1=>"a1", :b1=>[], :c1=>{:c2=>[0, 1]}}

Note that while parenthesis are often optional in Ruby, they're needed with Hash literals and #merge! to ensure the Hash to be merged is treated as an argument instead of a block by the parser/interpreter.

If you'd prefer to return a new Hash with the merged elements, then use Hash#merge instead. This will leave the original a untouched, while returning a copy of a merged with your Hash-literal argument.