返回可以是多个的所有最大值或最小值

当接收器中有多个最大/最小元素时,可Enumerable#max_byEnumerable#min_by返回相关元素之一(可能是第一个)。 例如,以下内容:

 [1, 2, 3, 5].max_by{|e| e % 3} 

仅返回2 (或仅返回5 )。

相反,我想返回所有最大/最小元素和数组。 在上面的例子中,它将是[2, 5] (或[5, 2] )。 得到这个的最好方法是什么?

 arr = [1, 2, 3, 5] arr.group_by{|a| a % 3} # => {1=>[1], 2=>[2, 5], 0=>[3]} arr.group_by{|a| a % 3}.max.last # => [2, 5] 
 arr=[1, 2, 3, 5, 7, 8] mods=arr.map{|e| e%3} 

找到最大值

 max=mods.max indices = [] mods.each.with_index{|m, i| indices << i if m.eql?(max)} arr.select.with_index{|a,i| indices.include?(i)} 

找分钟

 min = mods.min indices = [] mods.each.with_index{|m, i| indices << i if m.eql?(min)} arr.select.with_index{|a,i| indices.include?(i)} 

对不起笨拙的代码,会尽量缩短代码。

回答@Sergio Tulentsev是最好和最有效的答案,找到了在那里学习的东西。 +1

这是@Serio使用group_by的哈希等价物。

 arr = [1, 2, 3, 5] arr.each_with_object(Hash.new { |h,k| h[k] = [] }) { |e,h| h[e%3] << e }.max.last #=> [2, 5] 

步骤:

 h = arr.each_with_object(Hash.new { |h,k| h[k] = [] }) { |e,h| h[e%3] << e } #=> {1=>[1], 2=>[2, 5], 0=>[3]} a = h.max #=> [2, [2, 5]] a.last #=> [2, 5]