合并具有相同键的值的散列被附加

Merging hashes with values having the same key getting appended

我想知道实现此目标的最佳方法是什么:

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

我研究过使用合并!但这给了我输出:

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

merge 不是递归的,因此它仅将两个散列中的 fruitsvegetables 项与其默认行为合并。您需要为 merge! 提供一个块以进入下一级哈希并将它们与默认的 merge 合并。

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

expected_output = my_hash_1.merge(my_hash_2) { |_, h1, h2| h1.merge(h2) }

p expected_output

结果

{:fruits=>{:red=>"apple", :green=>"grapes"}, :vegetables=>{:green=>"spinach"}}
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"}}

这两个答案确实解决了我想做的事情,但由于我只使用两个散列并且知道要合并哪些键,所以我最终做了类似这样的事情,我发现这是一种更简单的方法。

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

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

my_hash_1[:fruits]&.merge!(my_hash_2[:fruits]) unless my_hash_2[:fruits].nil?

这实际上会将两者合并到 my_hash_1