Donato Donato - 8 months ago 24
Ruby Question

Ruby - Merge two hashes and maintain ordered keys

I have two hashes:

a = {"0"=>"name", "1"=>"email"}
b = {"0"=>"source", "1"=>"info", "2"=>"extra", "3"=>"name"}

I want a hash created by doing the following:

1) When the two hashes contain identical values, keep value of original hash and discard value of second hash.

2) When the values of second hash are not in first hash, just add to the end of new hash, making sure that the key is ordered.

with this result:

{"0"=>"name", "1"=>"email", "2"=>"source", "3"=>"info", "4"=>"extra"}

I did it this ugly way:

l1 = a.keys.length
l2 = b.keys.length
max = l1 > l2 ? l1 : l2
counter = l1
result = {}
max.times do |i|
unless a.values.include? b[i.to_s]
result[counter.to_s] = b[i.to_s]
counter += 1

Is there a built-in ruby method or utility that could achieve this same task in a cleaner fashion?

(a.values + b.values){|v, i| [i.to_s, v]}.to_h
# => {"0"=>"name", "1"=>"email", "2"=>"source", "3"=>"info", "4"=>"extra"}