Alex Rivera | Logout

indexOf in Ruby

Asked 2012-09-27T08:14:53.037
10

Just wondering is there the same method for an Array object similar to indexOf in JavaScript?

For example:

arr = %w{'a', 'b', 'c'}
c = 'c'
if (arr.indexOf(c) != -1)
// do some stuff
else
// don't do some stuff
Edit
Report

1 Answer

14

It is the .index method of Array.

http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-index

In ruby, only false and nil are considered as false value, so you could just do:

arr = %w{a, b, c}
c = 'c'
if arr.index c
  # do something
else 
  # do something else
end 
answered 2012-09-27T08:17:04.363

Your Answer