Ruby 搜索从给定索引开始的数组元素

Ruby 搜索从给定索引开始的数组元素,ruby,arrays,Ruby,Arrays,在Python中,可以在搜索列表元素时指定开始和结束索引: >>> l = ['a', 'b', 'a'] >>> l.index('a') 0 >>> l.index('a', 1) # begin at index 1 2 >>> l.index('a', 1, 3) # begin at index 1 and stop before index 3 2 >>> l.index('a', 1, 2)

在Python中,可以在搜索列表元素时指定开始和结束索引:

>>> l = ['a', 'b', 'a']
>>> l.index('a')
0
>>> l.index('a', 1) # begin at index 1
2
>>> l.index('a', 1, 3) # begin at index 1 and stop before index 3
2
>>> l.index('a', 1, 2) # begin at index 1 and stop before index 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'a' is not in list
>l=['a','b','a']
>>>l.索引('a')
0
>>>l.索引('a',1)#从索引1开始
2.
>>>l.索引('a',1,3)#从索引1开始,在索引3之前停止
2.
>>>l.索引('a',1,2)#从索引1开始,在索引2之前停止
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:“a”不在列表中
Ruby中是否有类似的功能?您可以使用数组切片,但这似乎效率较低,因为它需要中间对象。

试试看

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

arr[1,3].include? 2
=> true
arr[1,3].include? 1
=> false

Ruby中没有等效的特性

您可以从数组的开头开始搜索并使用向前搜索到结尾,也可以从数组的结尾开始搜索并使用向后搜索到开头。要从一个任意索引转到另一个索引,必须首先使用数组切片(例如with)将数组切片到感兴趣的索引,正如OP所建议的那样