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)"
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With