如何根据数组哈希格式中的键和值更改深度哈希格式?

时间:2014-07-08 09:23:23

标签: ruby-on-rails ruby hash nested-attributes

我有一个哈希作为输入

{"2"=>{"809"=>["16E", "16Es"], "954"=>["16C", "16Cs"], "955"=>["15B", "15Br"], 
 "627"=>["10B", "10Bt"]}, "1"=>{"955"=>["15C", "15Ca"], "627"=>["10C", "10Cb"]}}

我希望输出像:

{"809"=>{"2"=>["16E", "16Es"]}, "954"=>{"2"=>["16C", "16Cs"]}, 
 "955"=>{"2"=>["15B", "15Br"], "1"=>["15C", "15Ca"]}, 
 "627"=>{"2"=>["10B", "10Bt"], "1"=>["10C", "10Cb"]}}

我试过了:

{"1"=>{"627"=>["10C", "10Cb"], "955"=>["15C", "15Ca"]}, 
 "2"=>{"627"=>["10B", "10Bt"], "955"=>["15B", "15Br"], 
 "954"=>["16C", "16Cs"], 
 "809"=>["16E", "16Es"]}}.each_with_index{|item, index| hash[item]=index}

但我没有按预期获得输出。

2 个答案:

答案 0 :(得分:2)

这应该有效:

old_hash = {"2"=>{"809"=>["16E", "16Es"], "954"=>["16C", "16Cs"], "955"=>["15B", "15Br"], "627"=>["10B", "10Bt"]}, "1"=>{"955"=>["15C", "15Ca"], "627"=>["10C", "10Cb"]}}    
new_hash = {}
old_hash.each do |key,value|
  value.each do |k,v|
    new_hash[k] = {key => v}
  end  
end

答案 1 :(得分:1)

这可以为您提供您正在寻找的内容:

original_hash = {"2"=>{"809"=>["16E", "16Es"], "954"=>["16C", "16Cs"], "955"=>["15B", "15Br"], "627"=>["10B", "10Bt"]}, "1"=>{"955"=>["15C", "15Ca"], "627"=>["10C", "10Cb"]}}
original_hash.inject({}) do |hash, entry|
  entry[1].each do |k,v| 
    hash[k] ||= {}
    hash[k][entry[0]] = v 
  end
  hash
end

输出:

{"809"=>{"2"=>["16E", "16Es"]}, "954"=>{"2"=>["16C", "16Cs"]}, "955"=>{"2"=>["15B", "15Br"], "1"=>["15C", "15Ca"]}, "627"=>{"2"=>["10B", "10Bt"], "1"=>["10C", "10Cb"]}}