ruby add new key-value pair to nested hash

11,663

Solution 1

My guess is that you want to do something like this.

a = {:"0" => {:CA => {:count => 10}}}
b = {:"0" => {:NY => {:count => 11}}} 
a[:"0"][:NY] = b[:"0"][:NY] #=> {:"0"=>{:CA=>{:count=>10}, :NY=>{:count=>11}}}

You could also take advantage of merge

a = {:"0" => {:CA => {:count => 10}}}
b = {:"0" => {:NY => {:count => 11}}} 
a[:"0"] = a[:"0"].merge(b[:"0"]) #=> {:"0"=>{:CA=>{:count=>10}, :NY=>{:count=>11}}}

Solution 2

You are getting the nil:NilClass error because you are trying to set a key of hash that doesn't exist yet. You need to create the hash that is the value of the key :NY.

a[:"0"].merge!({:NY => {:count => 11}})

or

a[:"0"][:NY] = {:count => 11}
Share:
11,663
Bruce Lin
Author by

Bruce Lin

Updated on June 13, 2022

Comments

  • Bruce Lin
    Bruce Lin almost 2 years

    Suppose we have a nested hash here.

    a = {:"0" => {:CA => {:count => 10}}}
    

    if we want to add a new hash pair to that hash, say

    a = {:"0" => {:NY => {:count => 11}}} 
    

    and let it become

    a = {:"0" => {:CA => {:count =>10}, :NY => {:count => 11}}}
    

    what should I do?

    I've tried

    a[:0][:NY][:count] = 11
    

    but get the error "undefined method `[]=' for nil:NilClass (NoMethodError)"