如何在没有新键的情况下合并两个哈希 [英] How to merge two hashes with no new keys
本文介绍了如何在没有新键的情况下合并两个哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何合并两个没有新键的哈希,这意味着合并将合并两个哈希中都存在的键?
How could I merge two hashes that results in no new keys, meaning the merge would merge keys that exist in both hashes?
例如,我想要以下内容:
For example, I want the following:
h = {:foo => "bar"}
j = {:foo => "baz", :extra => "value"}
puts h.merge(j) # {:foo => "baz"}
我正在寻找一种非常干净的方式来执行此操作,因为我当前的实现非常混乱.
I'm looking for a really clean way of doing this as my current implementation is pretty messy.
推荐答案
您可以从第二个哈希中删除不在第一个哈希中的键,然后合并:
You could remove keys that weren't in the first hash from the second hash, then merge:
h.merge j.select { |k| h.keys.include? k }
与我编辑的替代方案不同,如果您决定将其更改为 merge!
或 update
,这是安全的.
Unlike my edited-out alternative, this is safe if you decide to change it to a merge!
or update
.
这篇关于如何在没有新键的情况下合并两个哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文