我有一系列哈希:
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'}
]
答案 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]}