linkyndy
linkyndy

Reputation: 17900

Add key to nested hash while iterating over a hash

Say I have a hash like:

myhash = {'key1': {'innerkey1': 'innervalue1', ...}, ...}

I would like to iterate over this hash and add a key-value pair to the inner hash. The above example becomes:

myhash = {'key1': {'innerkey1': 'innervalue1', 'addedkey': 'addedvalue', ...}, ...}

I tried with myhash.each do |k, v|, but changing v in the block affects the hash only within the block's scope. It works by doing myhash[k]['addedkey'] = 'addedvalue' inside the block, but I would like to modify the inner hash in place, not use myhash to do this.

How can I do this in Ruby?

Upvotes: 1

Views: 1389

Answers (1)

Rustam Gasanov
Rustam Gasanov

Reputation: 15781

Use Hash merge! method:

myhash = { k1: { innerk1: 'innerv1' },  k2: { innerk2: 'innerv2' } }

myhash.each do |key, value|
  value.merge!({ addedk: 'addedv' })
end

p myhash

# {:k1=>{:innerk1=>"innerv1", :addedk=>"addedv"}, :k2=>{:innerk2=>"innerv2", :addedk=>"addedv"}}

Upvotes: 4

Related Questions