如何在Ruby中不覆盖重复键的情况下合并两个哈希? [英] How can I merge two hashes without overwritten duplicate keys in Ruby?

查看:37
本文介绍了如何在Ruby中不覆盖重复键的情况下合并两个哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单或优雅的方式来合并两个散列而不覆盖重复键?

Is there an easy or elegant way to merge two hashes without overwriting duplicate keys?

也就是说,如果键存在于原始散列中,我不想更改其值.

That is, if the key is present in the original hash I don't want to change its value.

推荐答案

如果你有两个散列,optionsdefaults,并且你想合并 defaultsoptions 而不覆盖现有的键,你真正想要做的是相反的:将 options 合并到 defaults 中:

If you have two hashes, options and defaults, and you want to merge defaults into options without overwriting existing keys, what you really want to do is the reverse: merge options into defaults:

options = defaults.merge(options)

或者,如果您使用 Rails,您可以这样做:

Or, if you're using Rails you can do:

options.reverse_merge!(defaults)

这篇关于如何在Ruby中不覆盖重复键的情况下合并两个哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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