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