Home > Software design >  How to convert a Hash with values as arrays to a Hash with keys from array and values as array of ke
How to convert a Hash with values as arrays to a Hash with keys from array and values as array of ke

Time:06-06

I have a hash of the following form:

{ 1 => [], 2 => [A,B] 3 => [C] 4 => [B,C] 5 => [D] }

what's the best way to transform this in Ruby to:

{A=>[2],B=>[2,4],C=>[3,4],D=>[5],default=>[1]}

CodePudding user response:

The best way I know.

hash = { 1 => [], 2 => ['A','B'], 3 => ['C'], 4 => ['B','C'], 5 => ['D'] }

new_hash = hash.inject({}) do |result, (key, values)|
  values.each do |value|
    result[value] ||= []
    result[value].push(key)
  end
  result[:default] = [key] if values.empty?

  result
end

puts new_hash

CodePudding user response:

A bit of more functional approach:

array
  .flat_map {|k,v| v.product([k])}
  .group_by(&:first)
  .transform_values {|v| v.map(&:last) }
  • Related