如何通过两对`key =>过滤哈希数组?红宝石的价值`

时间:2018-03-13 04:06:08

标签: ruby-on-rails ruby

我有一系列哈希:

array = [
{:created_at => 1520913341, :event_id => '111', :album_id => '123'},
{:created_at => 1520740541, :event_id => '234', :album_id => '999'},
{:created_at => 1520654141, :event_id => '111', :album_id => '777'},
{:created_at => 1520394941, :event_id => '233', :album_id => '444'},
{:created_at => 1520049341, :event_id => '890', :album_id => '765'}
 ]

我需要保留所有:event_id的哈希值,如果:event_id重复,请保留最早的:created_at。我怎么能在红宝石中执行此操作?

我希望得到以下回复:

[
{:created_at => 1520740541, :event_id => '234', :album_id => '999'},
{:created_at => 1520654141, :event_id => '111', :album_id => '777'},
{:created_at => 1520394941, :event_id => '233', :album_id => '444'},
{:created_at => 1520049341, :event_id => '890', :album_id => '765'}
 ]

2 个答案:

答案 0 :(得分:5)

array.sort_by { |h| h[:created_at] }.uniq { |h| h[:event_id] }
  #=> [{:created_at=>1520049341, :event_id=>"890", :album_id=>"765"},
  #    {:created_at=>1520394941, :event_id=>"233", :album_id=>"444"},
  #    {:created_at=>1520654141, :event_id=>"111", :album_id=>"777"},
  #    {:created_at=>1520740541, :event_id=>"234", :album_id=>"999"}]

请参阅Array#uniq,特别是" self按顺序遍历,第一次出现。"。

答案 1 :(得分:3)

试试这个

array.group_by { |t| t[:event_id] }.map { |_,hash| hash.min_by { |t| t[:created_at]} }.sort_by {|t| -t[:created_at]}