Hash invert in Ruby?

后端 未结 8 1785
星月不相逢
星月不相逢 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 00:54

    Ok, let's guess. You say you have an array but I agree with Benoit that what you probably have is a hash. A functional approach:

     h = {:key1 => ["a", "b", "c"], :key2 => ["d", "e", "f"]}
     h.map { |k, vs| Hash[vs.map { |v| [v, k] }] }.inject(:merge)
     #=> {"a"=>:key1, "b"=>:key1, "c"=>:key1, "d"=>:key2, "e"=>:key2, "f"=>:key2}
    

    Also:

     h.map { |k, vs| Hash[vs.product([k])] }.inject(:merge)
     #=> {"a"=>:key1, "b"=>:key1, "c"=>:key1, "d"=>:key2, "e"=>:key2, "f"=>:key2}
    

提交回复
热议问题