Hash_invert
Inverting a Hash is simple: Hash#invert
By inverting: keys become values and values become keys.
I’ve seen some examples of people inverting hashes or doing other tricky things to find the key of a value.
For that you use .key(value)
hsh = {one: :uno, two: :doz, three: :tres}
p hsh.key(:doz) # => :two
Like in a database.. a key must be unique. A value do not need to be unique. You see the problem?
hsh = {cat: 'animal', square: 'shape', dog: 'animal'}
p hsh.invert # => {"animal" => :dog, "shape" => :square}
Do you prefer each_with_object or inject? Link to heading
p hsh.each_with_object({}) {|(k,v), res| (res[v] ||= []) << k }
p hsh.inject({}) {|m, (k,v) | m.tap { (it[v] ||= []) << k } }
# if you don't like a 16 char, 3-word method...
class Hash; alias :ewo :each_with_object; end
p hsh.ewo({}) {|(k,v), res| (res[v] ||= []) << k }
What you get is values as keys and the key(s) in Array.
like: {"animal": [:cat, :dog], "shape": [:square]}
If you know your values can take symbol-shape..
use: it[v.to_sym]
and get
{animal: [:cat, :dog], shape: [:square]}
And if you don’t know: it[v.to_sym || v]