如何合并两个哈希,没有新的键 [英] How to merge two hashes with no new keys

查看:113
本文介绍了如何合并两个哈希,没有新的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何合并两个哈希会导致没有新的键,这意味着合并将合并两个哈希中存在的键?

How could I merge two hashes that results in no new keys, meaning the merge would merge keys that exist in both hashes?

例如,我想要以下:

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.

推荐答案

您可以从第二个哈希中删除不在第一个哈希中的密钥,然后合并: p>

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!更新

Unlike my edited-out alternative, this is safe if you decide to change it to a merge! or update.

这篇关于如何合并两个哈希,没有新的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆