Reputation: 1004
I want to take the two hashes below and combine them into a new hash or array:
hash1 = {1=>"]", 2=>"}", 3=>")", 4=>"(", 5=>"{", 6=>"["}
hash2 = {1=>"[", 2=>"{", 3=>"(", 4=>")", 5=>"}", 6=>"]"}
I want the result to look something like this:
result = {"["=>"]", "{"=>"}", "("=>")"}
or
result = [ ["[","]"], ["{","}"], ["(",")"] ]
Is there a ruby method that can do this?
Upvotes: 1
Views: 267
Reputation: 168199
hash1.merge(hash2){|_, v1, v2| [v1, v2]}.values
# => [["]", "["], ["}", "{"], [")", "("], ["(", ")"], ["{", "}"], ["[", "]"]]
Upvotes: 0
Reputation: 3154
hash1.each_with_object({}) { |(k, v), h| h[hash2[k]] = v }
#=> {"["=>"]", "{"=>"}", "("=>")", ")"=>"(", "}"=>"{", "]"=>"["}
Or:
hash2.each_with_object({}) { |(k, v), h| h[v] = hash1[k] }
#=> {"["=>"]", "{"=>"}", "("=>")", ")"=>"(", "}"=>"{", "]"=>"["}
Upvotes: 1
Reputation: 180
Well, another way you can get what you want is by using Hash#deep_merge like so:
res = hash1.deep_merge(hash2) { |key, this_val, other_val| [other_val , this_val] }.values
# => [["[", "]"], ["{", "}"], ["(", ")"], [")", "("], ["}", "{"], ["]", "["]
res.first(3)
# => [["[", "]"], ["{", "}"], ["(", ")"]]
Upvotes: 1
Reputation: 11193
You could use Hash#transform_keys:
res = hash1.transform_keys { |k| hash2[k] }
res #=> {"["=>"]", "{"=>"}", "("=>")", ")"=>"(", "}"=>"{", "]"=>"["}
res.first(3) #=> [["[", "]"], ["{", "}"], ["(", ")"]]
Upvotes: 4