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

Ruby 返回所有可以是多个的最大值或最小值,ruby,max,min,maxby,Ruby,Max,Min,Maxby,Enumerable#max#u by和Enumerable#min#u by当接收器中存在多个max/min元素时,返回相关元素的一个(可能是第一个)。例如,以下各项: [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

Enumerable#max#u by
Enumerable#min#u by
当接收器中存在多个max/min元素时,返回相关元素的一个(可能是第一个)。例如,以下各项:

[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]
找到max
max=mods.max
指数=[]

mods.each.with_index{m,i|index这是@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]
arr=[1,2,3,5]
arr.each|u与_对象(Hash.new{h,k{h[k]=[]){e,h{h[e%3][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]
h=arr.each_与_对象(Hash.new{h,k{h[k]=[]){e,h{h%3]{1=>[1],2=>[2,5],0=>[3]}
a=h.max
#=> [2, [2, 5]]
a、 最后
#=> [2, 5]

您使用的
groupby
很好,但我认为您可以进一步改进,在键上用
max\u by
替换
sort
,或者只使用
arr.group\u by{a | a | a%3}.max.last
@steenslag更短,但从效率上看,使用Schwarzian变换不是更好吗?(我可能错了。不知道没有块它是如何工作的)@sawa你是对的。果味:max_by比max快19.99999999999999 6%±1.0%max比sort by快19.99999999999999 6%±1.0%@sawa:我刚刚意识到你是OP:)
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)}
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]