开发者

Hash map in ruby?

开发者 https://www.devze.com 2023-04-06 21:53 出处:网络
I\'m trying to get this object, passed via AJAX: Parameters: {\"status\"=>{\"1\"=>[\"14\", \"1\"], \"2\"=>[\"7\", \"8\", \"12\", \"13\"]}}

I'm trying to get this object, passed via AJAX:

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

into something like:

开发者_StackOverflow中文版
14 -> 1
1 -> 1
7 -> 2

over which I can iterate.

What's the most elegant way of achieving this?


flat_inverse = {}
parameters["status"].each { |key, values| values.each { |v| flat_inverse[v] = key } }

flat_inverse
# {"14"=>"1", "1"=>"1", "7"=>"2", "8"=>"2", "12"=>"2", "13"=>"2"}

#or more functional
Hash[*parameters["status"].map { |k, vs| vs.zip([k] * v.length) }.flatten]


Couple other variants, using product:

input.map{|k,v| Hash[v.product([k])]}.inject(&:merge)
# => {"14"=>"1", "1"=>"1", "7"=>"2", "8"=>"2", "12"=>"2", "13"=>"2"} 
Hash[input.map{|k,v| v.product([k])}.flatten(1)]
# => {"14"=>"1", "1"=>"1", "7"=>"2", "8"=>"2", "12"=>"2", "13"=>"2"} 


input = {"1"=>["14", "1"], "2"=>["7", "8", "12", "13"]}

output = Hash[*input.map{|k,l|l.map{|v|[v,k]}}.flatten]
=> {"14"=>"1", "1"=>"1", "7"=>"2", "8"=>"2", "12"=>"2", "13"=>"2"}

output.each {|k,v| puts "#{k} -> #{v}"}
14 -> 1
1 -> 1
7 -> 2
8 -> 2
12 -> 2
13 -> 2
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号