arrays - Ruby - 比较数组并根据条件获取索引
问题描述
我有两个数组
array_input = %w[one two three two]
array_compare = %w[one two three four five]
如果值存在于输入数组中,我想从 array_compare 数组中提取“最高”索引。所需的输出与输入数组和数组2
中存在的一样。three
compare
我试过了
val = nil
array_compare.reverse_each do |v|
val = v and break if array_input.include? v
end
但它没有设置 val。
解决方案
如果我理解正确,
从 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
。
推荐阅读
- c# - 在运行时修改导致 InvalidProgramException 的 IL 代码
- swift - 如何在新故事板中将数据传递给 ViewController
- angularjs - 我正在使用 d3.v3.min.js 来显示诸如思维导图结构之类的数据。我有大量数据,因此显示数据非常不方便
- mysql - SQL - 使用时间戳列创建具有默认值的列
- java - 集成测试db h2
- reactjs - 动态生成 JSX
- python - 如果字符串包含 Pandas 中其他列的值,则映射列
- xamarin - 将 android 项目引用到 ui 测试项目 Xamarin 时出错
- r - 冻结框内数据表的页眉和页脚() - Shiny Dashboard
- android - 错误 undefined is not an object (evalating 'this.props.navigation.navigate') // React-native