0

输入哈希数组是这样的:

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

我想把它转换成:

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

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

4

3 回答 3

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}}
于 2013-11-06T01:23:54.070 回答
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}}

这与@falsetru 的解决方案类似,但更通用的是,如果原始哈希中除了:countand之外还有更多键:date,它们都将保留在结果中:

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}}
于 2013-11-06T01:26:15.760 回答
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
于 2013-11-06T01:59:18.710 回答