ItGo.me Focus on IT Recommend

Home > ruby add new key-value pair to nested hash

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

ruby-on-rails ruby hash
edited Aug 10 '12 at 0:49 diedthreetimes 3,274 16 28 asked Aug 10 '12 at 0:39 Bruce Xinda Lin 835 2 14 25 2   You may want to look at the formatting guide. use backticks for inline code like this code here or cariage return plus 4 spaces. Also looking at the preview helps a lot. –  diedthreetimes Aug 10 '12 at 0:44

 | 

2 Answers
2

---Accepted---Accepted---Accepted---

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

Recommend:ruby on rails - How to get min key value pair in hash

, 'd' => 0.32, 'e' => 0.03, 'f' => 0.02, 'g'=> 0.1} Expected result: {'f'=> 0.02} How can I get the expected result I need all minimum key/value pairs. if {'a'=>1,'b'=>1,'c'=>2} the expected result should be {'a'=>1,'b'=>1}. ruby-on-rail

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}}}

edited Aug 10 '12 at 1:52 answered Aug 10 '12 at 0:46 diedthreetimes 3,274 16 28

 | 

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}

answered Aug 10 '12 at 1:30 Lukas Eklund 4,372 21 30      How is this any different then what i said? –  diedthreetimes Aug 10 '12 at 1:47      Before you're edit they were slightly different. Now the only difference is that my answer isn't creating an extra, and in my opinion, unnecessary hash before assigning or merging. –  Lukas Eklund Aug 10 '12 at 2:15

 | 

Recommend:ruby - rails: add key val pair to serialized hash in database

es stored in a database. Now I want to extend the hash data with a new key-value pair (calculated from stored data), e.g. like this in Ruby: Data stored database: coordinates = Array.newc1 = Hash.new('x' => x1, 'y' => y1)c2 = Hash.new('x

oriUlr:http://stackoverflow.com/questions/11893978/ruby-add-new-key-value-pair-to-nested-hash

------splitte line----------------------------