Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Collections Ruby Arrays Accessing Items in Arrays

Is there a way to find the position of a specific string or number stored in an array?

Is there a way to find the position of a specific string or number stored in an array? (without the aid of some type of for loop to test each element of the array)

I'm just curious because there is a way to do this Mathematica and it can be helpful. Thanks in advance for any light someone might be able to shed on this.

1 Answer

Seth Shober
Seth Shober
30,240 Points

Hi Kristoffer,

There is a way to check this in ruby with index, rather than writing your own for loop. Though I haven't checked the ruby source code, I have a hunch under the hood this is just going to run a for loop for you.

animals = ['dog', 'cat', 'eagle']
 animal = 'eagle'

animals.index(animal) => 2

# you might also be interested in include

animals.include? animal => true

Forgive me if this is too basic or if I have misspoke. I am not a rubyist.

Thank you Seth, that is exactly what I was looking for. The video I was watching when I came up with this question had the ".include?" and I was kind of thinking "Ok, so we know it's in there. How do we find it?"