Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create key if it doesn't exist in nested hashes

I've been trying to figure out how to write this ruby code more eloquently. Does someone have a better solution?

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

is there a way to write this in a more elegant way? I come across this a lot when dealing with nested hashes that need to check whether an key exist and if not, create it.

like image 596
Roger Killer Avatar asked Sep 15 '25 08:09

Roger Killer


2 Answers

Write it as below taking the help of Hash#to_h and 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}}
like image 166
Arup Rakshit Avatar answered Sep 17 '25 22:09

Arup Rakshit


Do this at the beginning:

a = Hash.new{|h, k| h[k] = {}}

then, without caring whether a has a key :new or not, do

a[:new].merge!(new_key => new_value)

or

a[:new][new_key] = new_value
like image 34
sawa Avatar answered Sep 17 '25 23:09

sawa