Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Foundations Arrays Working With Arrays

Christ khodabakhshi
Christ khodabakhshi
10,916 Points

index vs rindex

I am wondering to know what is the difference of index and rindex methods in array object (I searched but i couldn't find something).

1 Answer

index searches the array for the object starting at element 0 and working up, where rindex will start at the end of the array and work down searching for the object. They can both return the same result if the object you're searching for only exists in the array once. But if, however, it exists multiple times you'll get different indices when using index as it only returns the index first occurrence of the object you're searching for.

Some IRB output to help illustrate:

>> array = ['a', 'b', 'c', 'd', 'e', 'a']
=> ["a", "b", "c", "d", "e", "a"]
>> array.index('a')
=> 0
>> array.rindex('a')
=> 5
>> array.index('c')
=> 2
>> array.rindex('c')
=> 2
Christ khodabakhshi
Christ khodabakhshi
10,916 Points

Thank you, very clear explanation :)