Ruby - How to invert a Hash with an array values?

arrays, hash, ruby, ruby-1.8

Solution

h = {"Book Y"=>["author B", "author C"], "Book X"=>["author A", "author B", "author C"]}

p h.inject(Hash.new([])) { |memo,(key,values)|
  values.each { |value| memo[value] += [key] }
  memo
}
# => {"author B"=>["Book Y", "Book X"], "author C"=>["Book Y", "Book X"], "author A"=>["Book X"]}

Problem

Looking for an answer that works on Ruby 1.8.7 : For example lets say I have a hash like this: ``` {"Book Y"=>["author B", "author C"], "Book X"=>["author A", "author B", "author C"]} ``` and I want to get this: ``` { "author A" => ["Book X"], "author B" => ["Book Y", "Book X"], "author C" => ["Book Y", "Book X"] } ``` I wrote a really long method for it, but with large datasets, it is super slow. Any elegant solutions?

Original source