Reputation: 115
I have two hashes that look like this:
h1 = {key1: 'Roses are', key2: 'Violets are'}
h2 = {key1: 'Red', key2: 'Blue'}
I would like to join them by keys so that I get a hash like this:
result = {'Roses are' => 'Red', 'Violets are' => 'Blue'}
I have some code that does the trick:
result = {}
h1.each { |key, value| result[value] = h2[key] }
I wonder if there is a method in the standard lib to do this or whether this can be done with less code.
Upvotes: 0
Views: 90
Reputation: 114138
You want a 1:1 mapping, so map
would work:
h1.map { |k, v| ... }
The values from h1
become the new keys:
h1.map { |k, v| [v, ...] }
The corresponding values from h2
become the new values:
h1.map { |k, v| [v, h2[k]] }
#=> [["Roses are", "Red"], ["Violets are", "Blue"]]
And to_h
converts that back into a hash:
h1.map { |k, v| [v, h2[k]] }.to_h
#=> {"Roses are"=>"Red", "Violets are"=>"Blue"}
Upvotes: 5
Reputation: 80065
Zip the values:
h1 = {key1: 'Roses are', key2: 'Violets are'}
h2 = {key1: 'Red', key2: 'Blue'}
result = h1.values.zip(h2.values).to_h
Upvotes: 1