ruby - 惯用 ruby : data structure transformation

标签 ruby data-structures hash merge transformation

进行以下数据结构转换的“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/

相关文章:

ruby - 如何递归地将作为符号的 Ruby Hashes 的键转换为 String

ruby-on-rails - Rails 应用程序未在默认的 80 端口上运行。但在 80 以外的所有端口上运行

c - 删除堆栈给定索引处的元素,该索引是堆栈链表的一部分

c - c中栈数据结构解释

ruby - "Don' t run bundler as root”- 使用 root 的确切区别是什么?

c++ - 默认情况下,std::vector 是线程安全和并发的吗?为什么或者为什么不?

python - 对哈希 (MD5) 电子邮件地址进行取消哈希处理

c - 最适合基于前缀的搜索的数据结构

ruby - 从 Ruby 中的 MongoDB 嵌套哈希中提取正确的字符串

ruby - Ruby 的稀疏矩阵库