返回所有可以是倍数的最大值或最小值 [英] Returning all maximum or minimum values that can be multiple

查看:74
本文介绍了返回所有可以是倍数的最大值或最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Enumerable#max_byEnumerable#min_by返回相关元素的一个(可能是第一个).例如,以下内容:

Enumerable#max_by and Enumerable#min_by return one of the relevant elements (presumably the first one) when there are multiple max/min elements in the receiver. For example, the following:

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

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

相反,我想返回所有个max/min元素并以数组形式返回.在上面的示例中,它将为[2, 5](或[5, 2]).最好的方法是什么?

Instead, I want to return all max/min elements and in an array. In the example above, it would be [2, 5] (or [5, 2]). What is the best way to get this?

推荐答案

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]

这篇关于返回所有可以是倍数的最大值或最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆