Hash map in ruby?
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
精彩评论