从数组中删除最低值

时间:2014-07-09 11:56:18

标签: ruby-on-rails ruby arrays

说我有这个哈希数组:

[{:title => "Frankenstein", :edition => 1}, {:title => "Frankenstein", :edition => 2}, {:title => "Dracula", :edition => 1}, {:title => "Dracula", :edition => 2}, {:title => "Dracula", :edition => 3}]

是否有一种优雅的方式可以剥离所有旧版本的数组,只保留最高版本(最新版本)?

[{:title => "Frankenstein", :edition => 2}, {:title => "Dracula", :edition => 3}]

2 个答案:

答案 0 :(得分:2)

可以这样做:

array.group_by{|h| h[:title]}.values.map{|a| a.max_by{|h| h[:edition]}}
# => [{:title=>"Frankenstein", :edition=>2}, {:title=>"Dracula", :edition=>3}]

答案 1 :(得分:0)

使用以下代码

,您可以获得任何特定类型版本的最高价值
array = [{:title => "Frankenstein", :edition => 1}, {:title => "Frankenstein", :edition => 2}, {:title => "Dracula", :edition => 1}, {:title => "Dracula", :edition => 2}, {:title => "Dracula", :edition => 3}]

array.select{|x| x[:title] == "Dracula"}.max_by{|x| x[:edition]}