查找与给定条件匹配的元素的索引 [英] Find indices of elements that match a given condition
本文介绍了查找与给定条件匹配的元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个数组,如何找到与给定条件匹配的元素的所有索引?
Given an array, how can I find all indices of elements those match a given condition?
例如,如果我有:
arr = ['x', 'o', 'x', '.', '.', 'o', 'x']
要查找项目为 x
的所有索引,我可以这样做:
To find all indices where the item is x
, I could do:
arr.each_with_index.map { |a, i| a == 'x' ? i : nil }.compact # => [0, 2, 6]
或
(0..arr.size-1).select { |i| arr[i] == 'x' } # => [0, 2, 6]
有没有更好的方法来实现这一目标?
Is there a nicer way to achieve this?
推荐答案
Ruby 1.9:
arr = ['x', 'o', 'x', '.', '.', 'o', 'x']
p arr.each_index.select{|i| arr[i] == 'x'} # =>[0, 2, 6]
这篇关于查找与给定条件匹配的元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文