We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.
Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. The orders of each hashes are not compared.
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)
There is a way in standard Ruby library to merge Hashes without overwriting existing values or reassigning the hash.
important_hash.merge!(defaults) { |key, important, default| important }
If your problems is that the original hash and the second one both may have duplicate keys and you don't want to overwrite in either direction, you might have to go for a simple manual merge with some kind of collision check and handling:
hash2.each_key do |key|
if ( hash1.has_key?(key) )
hash1[ "hash2-originated-#{key}" ] = hash2[key]
else
hash1[key]=hash2[key]
end
end
Obviously, this is very rudimentary and assumes that hash1 doesn't have any keys called "hash2-originated-whatever" - you may be better off just adding a number to the key so it becomes key1, key2 and so on until you hit on one that isn't already in hash1. Also, I haven't done any ruby for a few months so that's probably not syntactically correct, but you should be able to get the gist.
Alternatively redefine the value of the key as an array so that hash1[key] returns the original value from hash1 and the value from hash2. Depends what you want your outcome to be really.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With