rubyhashmergehash-of-hashes

Merging hashes with values having the same key getting appended


I wanted to know what would be the best way to achieve this:

my_hash_1 = { fruits: { red: 'apple' }, vegetables: { green: 'spinach' } }

my_hash_2 = { fruits: { green: 'grapes' } }

expected_output = { fruits: { red: 'apple', green: 'grapes' }, vegetables: { green: 'spinach' } }

I have looked into using merge! but that gives me with output:

{:fruits=>{:green=>"grapes"}, :vegetables=>{:green=>"spinach"}}

Solution

  • my_hash_1 = { fruits: { red: 'apple' }, vegetables: { green: 'spinach' } }
    my_hash_2 = { fruits: { green: 'grapes' } }
    my_hash_3 = { fruits: { yellow: 'mango' },spice: { red: 'chilli' }}
    
    # extended method (multiple hash)
    def merge_hash(arr_of_hash)
        result = {}
        arr_of_hash.each do |_hash|
            _hash.each{ |k,v| result[k].nil? ? result[k] = v : result[k].merge!(v) }
        end
        result
    end
    puts merge_hash([my_hash_1,my_hash_2,my_hash_3])
    # {:fruits=>{:red=>"apple", :green=>"grapes", :yellow=>"mango"}, :vegetables=>{:green=>"spinach"}, :spice=>{:red=>"chilli"}}