ruby on rails - Create key if it doesn't exist in nested hashes -


i've been trying figure out how write ruby code more eloquently. have better solution?

a[:new] = {} if a[:new].nil? a[:new].merge!( { new_key => new_value } ) 

is there way write in more elegant way? come across lot when dealing nested hashes need check whether key exist , if not, create it.

write below taking of hash#to_h , nilclass#to_h

a[:new] = a[:new].to_h.merge( { new_key => new_value } ) 

example :

hsh1[:a] # => nil hsh1[:a] = hsh1[:a].to_h.merge({1=>2}) hsh1[:a] # => {1=>2}  hsh2 = {:a => {'k' => 2}} hsh2[:a] # => {"k"=>2} hsh2[:a] = hsh2[:a].to_h.merge({1=>2}) hsh2 # => {:a=>{"k"=>2, 1=>2}} 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -