Hash invert in Ruby?

后端 未结 8 1786
星月不相逢
星月不相逢 2021-01-13 00:27

I\'ve got a hash of the format:

{key1 => [a, b, c], key2 => [d, e, f]}

and I want to end up with:

{ a => key1, b =         


        
8条回答
  •  执笔经年
    2021-01-13 01:14

    One way to achieve what you're looking for:

    arr = [{["k1"] => ["a", "b", "c"]}, {["k2"] => ["d", "e", "f"]}]
    
    results_arr = []
    arr.each do |hsh|
      hsh.values.flatten.each do |val|
        results_arr << { [val] => hsh.keys.first }···
      end
    end
    
    
    Result: [{["a"]=>["k1"]}, {["b"]=>["k1"]}, {["c"]=>["k1"]}, {["d"]=>["k2"]}, {["e"]=>["k2"]}, {["f"]=>["k2"]}]
    

提交回复
热议问题