Ruby将哈希数组转换为一个哈希值

时间:2013-11-06 01:20:16

标签: ruby arrays hash

输入哈希数组是这样的:

[{count: 111, date: A},{count: 222, date: B},{count: 333, date: C}]

我想将其转换为:

{A => {count: 111}, B => {count: 222}, C => {count: 333}}

这只是一个简化版本,哈希可能非常大 - 我的意思是很多键。

3 个答案:

答案 0 :(得分:2)

a = [{count: 111, date: 'A'},{count: 222, date: 'B'},{count: 333, date: 'C'}]
Hash[a.map {|h| [h[:date], {count: h[:count]}]}]
# => {"A"=>{:count=>111}, "B"=>{:count=>222}, "C"=>{:count=>333}}

答案 1 :(得分:2)

aoh = [{count: 111, date: 'A'},{count: 222, date: 'B'},{count: 333, date: 'C'}]
flat = Hash[aoh.map {|h| [h.delete(:date), h]}]
# => {"A"=>{:count=>111}, "B"=>{:count=>222}, "C"=>{:count=>333}}

这与@fattru的解决方案相似,但稍微更一般的是,如果原始哈希中除了:count:date之外还有更多的键,它们都将保留在结果中:< / p>

aoh = [{count: 111, date: 'A', pos: 1},{count: 222, date: 'B', pos: 2},{count: 333, date: 'C', pos: 3}]
flat = Hash[aoh.map {|h| [h.delete(:date), h]}]
# => {"A"=>{:count=>111, :pos=>1}, "B"=>{:count=>222, :pos=>2}, "C"=>{:count=>333, :pos=>3}}

答案 2 :(得分:0)

Array#inject方法是个不错的选择:

[{count: 111, date: 'A'},{count: 222, date: 'B'},{count: 333, date: 'C'}].inject({}) do |h, item|
  h[item[:date]] = {count: item[:count]}
  h
end