You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby 如何从数组中提取多个最大值及其对应索引

Ruby 筛选数组所有最大值及对应索引的实现方案

给定示例数组:array = [22, 55, 55, 16]

推荐实现(性能最优)

  • 首先提前获取数组最大值,避免遍历过程中重复计算
max_value = array.max
  • 遍历数组同时保留索引,筛选出所有值等于最大值的条目
matched_result = array.each_with_index.select { |value, index| value == max_value }

执行后matched_result的输出为 [[55, 1], [55, 2]],每个子数组第一位为最大值,第二位为对应索引位置。

  • 如需单独提取最大值列表和索引列表,可以追加以下代码:
# 提取所有最大值
all_max_values = matched_result.map(&:first)
# 提取所有对应索引
all_max_indexes = matched_result.map(&:last)

运行后all_max_values结果为 [55, 55],all_max_indexes结果为 [1, 2]

简化写法(仅需索引时可用)

如果不需要保留最大值,只需要获取最大值对应的索引,可以用以下简化写法,仅适合小数组使用:

max_indexes = array.each_index.select { |index| array[index] == array.max }

内容的提问来源于stack exchange,提问作者def avi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:24:03