查找符合给定条件的元素的索引 [英] 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的:
Ruby 1.9:
arr = ['x', 'o', 'x', '.', '.', 'o', 'x']
p arr.each_index.select{|i| arr[i] == 'x'} # =>[0, 2, 6]
这篇关于查找符合给定条件的元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文