Hash invert in Ruby?

后端 未结 8 1782
星月不相逢
星月不相逢 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:03

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

    first variant

    hash.map{|k, v| v.map{|f| {f => k}}}.flatten
    #=> [{"a"=>:key1}, {"b"=>:key1}, {"c"=>:key1}, {"d"=>:key2}, {"e"=>:key2}, {"f"=>:key2}] 
    

    or

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

    UPD

    ok, your hash is:

    hash = {"status"=>{"1"=>["1", "14"], "2"=>["7", "12", "8", "13"]}}
    hash["status"].inject({}){|h, (k,v)| v.map{|f| h[f] = k}; h}
    #=> {"12"=>"2", "7"=>"2", "13"=>"2", "8"=>"2", "14"=>"1", "1"=>"1"}
    

提交回复
热议问题