如何在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)