在Ruby中使用Hash反转?

前端之家收集整理的这篇文章主要介绍了在Ruby中使用Hash反转?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个格式的哈希:
{key1 => [a,b,c],key2 => [d,e,f]}

我想最终得到:

{ a => key1,b => key1,c => key1,d => key2 ... }

实现这一目标的最简单方法是什么?

我正在使用Ruby on Rails.

UPDATE

好吧,我设法从服务器日志中提取真实对象,它是通过AJAX推送的.

Parameters: {"status"=>{"1"=>["1","14"],"2"=>["7","12","8","13"]}}

解决方法

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

第一个变种

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

要么

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

好的,你的哈希是:

hash = {"status"=>{"1"=>["1","13"]}}
hash["status"].inject({}){|h,v)| v.map{|f| h[f] = k}; h}
#=> {"12"=>"2","7"=>"2","13"=>"2","8"=>"2","14"=>"1","1"=>"1"}
原文链接:https://www.f2er.com/ruby/267698.html

猜你在找的Ruby相关文章