Hommer Smith Hommer Smith - 1 month ago 20
Ruby Question

Reverse hash in Ruby

Given a Hash like this:

{ "key_1" => ["value1","value2","value3"], "key_2" => ["value4","value5"], ...}


How can I get a hash like this:

{ "value1" => "key_1", "value2" => "key_1", "value3" => "key_1", "value4" => "key_2", "value5" => "key_2" }


I have tried this:

Hash[original_hash.flat_map { |key, values| original_hash.map { |value| [value, key] } }]

Answer
hash.each_with_object({}) { |(key,values),h| values.each { |v| h[v] = key } }
Comments