首页 > 解决方案 > Ruby - 比较数组并根据条件获取索引

问题描述

我有两个数组

array_input = %w[one two three two]
array_compare = %w[one two three four five]

如果值存在于输入数组中,我想从 array_compare 数组中提取“最高”索引。所需的输出与输入数组和数组2中存在的一样。threecompare

我试过了

val = nil
array_compare.reverse_each do |v|
  val = v and break if array_input.include? v
end

但它没有设置 val。

标签: arraysrubysetcompare

解决方案


如果我理解正确,

从 array_compare 数组中提取“最高”索引,如果该值存在于输入数组中,

这可能是一个选择:

array_compare.map.with_index { |e, id| id if array_input.include? e }.compact.max #=> 2

如果array_compare = %w[one two three four five three],则返回5


推荐阅读