Ruby 如果指定了键';s值在数组中是相同的

Ruby 如果指定了键';s值在数组中是相同的,ruby,arrays,hash,Ruby,Arrays,Hash,我有这样一个哈希数组: [ {:foo=>2, :date=>Sat, 01 Sep 2014}, {:foo2=>2, :date=>Sat, 02 Sep 2014}, {:foo3=>3, :date=>Sat, 01 Sep 2014}, {:foo4=>4, :date=>Sat, 03 Sep 2014}, {:foo5=>5, :date=>Sat, 02 Sep 2014}] 如果:date相同,我想合并散列

我有这样一个哈希数组:

[ {:foo=>2, :date=>Sat, 01 Sep 2014},
 {:foo2=>2, :date=>Sat, 02 Sep 2014},
 {:foo3=>3, :date=>Sat, 01 Sep 2014},
 {:foo4=>4, :date=>Sat, 03 Sep 2014},
  {:foo5=>5, :date=>Sat, 02 Sep 2014}]
如果
:date
相同,我想合并散列。 我对上述阵列的期望是:

[ {:foo=>2, :foo3=>3, :date=>Sat, 01 Sep 2014},
 {:foo2=>2, :foo5=>5 :date=>Sat, 02 Sep 2014},
 {:foo4=>4, :date=>Sat, 03 Sep 2014}]
我怎么做


也许我应该重新考虑数据结构本身?例如,我应该使用
date
值作为散列的键吗?

以下是如何在一行()中执行此操作:

此代码执行以下操作:

  • 按其
    :date
    值对所有哈希进行分组
  • 对于每个
    :date
    组,获取其中的所有哈希值,并将它们合并为一个哈希值

编辑:应用tokland和Cary Swoveland建议的修改。谢谢

您可以使用(也称为
merge!
)的形式,使用块解析合并的两个哈希中包含的键的值

arr = [ {:foo=>2, :date=>'Sat, 01 Sep 2014'},
        {:foo2=>2, :date=>'Sat, 02 Sep 2014'},
        {:foo3=>3, :date=>'Sat, 01 Sep 2014'},
        {:foo4=>4, :date=>'Sat, 03 Sep 2014'},
        {:foo5=>5, :date=>'Sat, 02 Sep 2014'}]

arr.each_with_object({}) do |g,h|
  h.update({ g[:date]=>g }) { |_,o,n| o.merge(n) }
end.values
  #=> [{:foo=>2,  :date=>"Sat, 01 Sep 2014", :foo3=>3},
  #    {:foo2=>2, :date=>"Sat, 02 Sep 2014", :foo5=>5},
  #    {:foo4=>4, :date=>"Sat, 03 Sep 2014"}]

我对包含键值的块变量使用了占位符

不,它是
日期
类。为什么?您的哈希定义无效。当我们试图帮助您时,它们是可重用的,这一点很重要,所以请确保Ruby会接受它们。挑剔:
hashes.group_by{h | h[:date]}.map{k,hs | hs.reduce(:merge)}
很好的解决方案。你可以考虑 >,HS > /COD>来告诉读者你没有使用这个块中的键。这是一个相当小的块,所以这可能是显而易见的,但仍然…小问题-如果:日期不是一个符号,请使用“日期”
arr = [ {:foo=>2, :date=>'Sat, 01 Sep 2014'},
        {:foo2=>2, :date=>'Sat, 02 Sep 2014'},
        {:foo3=>3, :date=>'Sat, 01 Sep 2014'},
        {:foo4=>4, :date=>'Sat, 03 Sep 2014'},
        {:foo5=>5, :date=>'Sat, 02 Sep 2014'}]

arr.each_with_object({}) do |g,h|
  h.update({ g[:date]=>g }) { |_,o,n| o.merge(n) }
end.values
  #=> [{:foo=>2,  :date=>"Sat, 01 Sep 2014", :foo3=>3},
  #    {:foo2=>2, :date=>"Sat, 02 Sep 2014", :foo5=>5},
  #    {:foo4=>4, :date=>"Sat, 03 Sep 2014"}]