roxxypoxxy
roxxypoxxy

Reputation: 3111

Creating a hash class constant from a hash with array keys

I have a class with a constant which is a hash:

  class ServiceMap
    MARKET_MAP = 
     {
       "Fords" => [11,2,43],
       "Edison" => [3,15]
     }

  end

I would like to generate a new constant dynamically that would look something like this:

CODE_MAP = {
 11: "Fords",
 2: "Fords",
 43: "Fords",
 3: "Edison",
 15: "Edison"
}

Until now I have this code but not able to figure out the right way of doing this and the best way to create a hash from a hash with array keys.

 def self.CODE_MAP
   @CODE_MAP ||= MARKET_MAP.inject({}){ do_something }
 end

Upvotes: 0

Views: 80

Answers (3)

hirolau
hirolau

Reputation: 13901

I would write:

Hash[MARKET_MAP.flat_map{|x,y| y.product [x] }]

Upvotes: 2

Anthony
Anthony

Reputation: 15967

You can use Enumberable#each_with_object

MARKET_MAP.each_with_object({}) do |(name, num_arr), hash| 
  num_arr.each { |num| hash[num] = name }
end
=> {11=>"Fords", 2=>"Fords", 43=>"Fords", 3=>"Edison", 15=>"Edison"}

Upvotes: 3

maerics
maerics

Reputation: 156434

CODE_MAP = MARKET_MAP.reduce({}) do |memo,(k,v)|
  v.each { |x| memo[x] = k }
  memo
end
# => {
#  11: "Fords",
#  2: "Fords",
#  43: "Fords",
#  3: "Edison",
#  15: "Edison"
# }

Upvotes: 2

Related Questions