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