如何在数组中找到与条件匹配的元素的索引并从数组中的特定点开始搜索?

How do I find an index of an element in an array matching a condition and starting the search from a particular point in the array?

我正在使用 Ruby 2.4。我知道如何在匹配条件的元素数组中找到所有索引 ...

arr.each_index.select{|i| arr[i] == 'x'}

但是如何从数组中的特定位置开始找到与条件匹配的第一个元素的索引?那么,如果我想查找在索引 = 2 处或之后只有一个字符的字符串怎么办? (如果元素少于 2 个,操作可以 return nil)。例如,如果我有

["abc", "d", "efg", "h", "abcde"]

该操作将 return "3",因为元素 "h" 位于位置 3,只有一个字符并且在索引 2 处或之后。

使用 select 将 return 块 returns true 中的所有值,例如:

p arr = ["abc", "d", "efg", "h", "abcde", "k"]
# => ["abc", "d", "efg", "h", "abcde", "k"]
p arr.each_index.select{|i| i >= 2 and arr[i].length == 1}
# => [3, 5]

如果您只想 return 块 returns true:

的第一个值,请改用 detect
p arr = ["abc", "d", "efg", "h", "abcde", "k"]
# => ["abc", "d", "efg", "h", "abcde", "k"]
p arr.each_index.detect{|i| i >= 2 and arr[i].length == 1}
# => 3
def first_index_after(arr, min_ndx)
  min_ndx.upto(arr.size-1).find { |i| yield(arr[i]) }
end

arr = ["abcdef", "h", "efgh", "h", "abcde", "h"]
min_ndx = 2

first_index_after(arr, min_ndx) { |e| e == "h" }     #=> 3 
first_index_after(arr, min_ndx) { |e| e =~ /\Ah\z/ } #=> 3 
first_index_after(arr, min_ndx) { |e| e =~ /h/ }     #=> 2 
first_index_after(arr, min_ndx) { |e| e.size > 4 }   #=> 4 
first_index_after(arr, min_ndx) { |e| e == 'cat' }   #=> nil 

这假设 0 <= min_ndx < arr.size。可能需要在 returns nil 的方法中添加第一行,或者如果不满足此要求则引发异常。

Array#indexwith_index 一起使用:

arr = ["abc", "d", "efg", "h", "abcde"]
arr.index.with_index { |el, idx| el.length == 1 && idx > 2 }
 => 3 

arr = ["abc", "d"]
arr.index.with_index { |el, idx| el.length == 1 && idx > 2 }
 => nil