Search for an array element starting at a given index

In Python, you can specify start and end indices when searching for a list item:

>>> 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 

Is there an equivalent function in Ruby? You can use slices of the array, but it looks like it will be less efficient due to the need to use intermediate objects.

+7
arrays ruby
source share
2 answers

There is no equivalent function in Ruby.

You can search from the beginning of the array and forward to the end of #index or search from the end of the array and return to the beginning with #rindex . To move from one arbitrary index to another, you first need to cut the array to the indices of interest using arrays of arrays (for example, using #[] ), as the OP suggested.

+1
source share

try it

 arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] arr[1,3].include? 2 => true arr[1,3].include? 1 => false 
0
source share

All Articles