Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for an Array element beginning at a given index

Tags:

arrays

ruby

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

>>> 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 feature in Ruby? You can use array slices, but that seems as though it would be less efficient, because of its requiring intermediate objects.

like image 464
Patrick Brinich-Langlois Avatar asked Jul 16 '13 10:07

Patrick Brinich-Langlois


1 Answers

There is not an equivalent feature in Ruby.

You can search from the start of the array and forward to the end with #index, or search from the end of the array and go backward to the start with #rindex. To go from one arbitrary index to another, you have to first slice the array down to the indices of interest using array slices (for example with #[]) as the OP suggested.

like image 148
user513951 Avatar answered Sep 20 '22 23:09

user513951