How can I merge two hashes without overwritten duplicate keys in Ruby?

前端 未结 5 792
不知归路
不知归路 2020-12-07 12:51

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

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 13:27

    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)
    

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

    options.reverse_merge!(defaults)
    

提交回复
热议问题