Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby add new key-value pair to nested hash

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)"

like image 550
Bruce Xinda Lin Avatar asked Aug 10 '12 00:08

Bruce Xinda Lin


1 Answers

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}
like image 77
Lukas Eklund Avatar answered Oct 27 '22 23:10

Lukas Eklund