进行以下数据结构转换的“Rubyist”方法是什么:
我有
incoming = [ {:date => 20090501, :width => 2}, {:date => 20090501, :height => 7}, {:date => 20090501, :depth => 3}, {:date => 20090502, :width => 4}, {:date => 20090502, :height => 6}, {:date => 20090502, :depth => 2}, ]
我想在 :date 之前折叠这些,以结束
outgoing = [ {:date => 20090501, :width => 2, :height => 7, :depth => 3}, {:date => 20090502, :width => 4, :height => 6, :depth => 2}, ]
只要列在每一行中的顺序相同,数组的数组在最后一步也可以。此外,重要的是,我事先并不知道所有的哈希键(也就是说,我不知道 :width、:height 或 :depth——它们可能是 :cats、:dogs 和 :hamsters)。
最佳答案
如果使用 Ruby 1.8.7 或 Ruby 1.9+,则以下代码读起来很好:
incoming.group_by{|hash| hash[:date]}.map do |_, hashes|
hashes.reduce(:merge)
end
block 属性中的下划线(_、散列)表示我们不需要/不关心该特定属性。
#reduce 是#inject 的别名,用于将集合减少 为单个项目。在新的 Ruby 版本中,它还接受一个符号,这是用于进行归约的方法的名称。
它首先调用集合中第一项的方法,第二项作为参数。然后,它以第三项作为参数再次调用该方法,直到没有更多项为止。
[1, 3, 2, 2].reduce(:+) => [4, 2, 2] => [6, 2] => 8
关于ruby - 惯用 ruby : data structure transformation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/990802/