[英]How to Change deep hash format based on key and values in hash of array, hash format?
I have a hash as input : 我有一个哈希作为输入 :
{"2"=>{"809"=>["16E", "16Es"], "954"=>["16C", "16Cs"], "955"=>["15B", "15Br"],
"627"=>["10B", "10Bt"]}, "1"=>{"955"=>["15C", "15Ca"], "627"=>["10C", "10Cb"]}}
and I want Output like: 我想要像这样的输出:
{"809"=>{"2"=>["16E", "16Es"]}, "954"=>{"2"=>["16C", "16Cs"]},
"955"=>{"2"=>["15B", "15Br"], "1"=>["15C", "15Ca"]},
"627"=>{"2"=>["10B", "10Bt"], "1"=>["10C", "10Cb"]}}
I tried like: 我尝试过:
{"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}
But I am not getting output as expected. 但是我没有得到预期的输出。
This should work: 这应该工作:
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
This should give you what you're looking for: 这应该给您您想要的东西:
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
Output: 输出:
{"809"=>{"2"=>["16E", "16Es"]}, "954"=>{"2"=>["16C", "16Cs"]}, "955"=>{"2"=>["15B", "15Br"], "1"=>["15C", "15Ca"]}, "627"=>{"2"=>["10B", "10Bt"], "1"=>["10C", "10Cb"]}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.