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

4 Answers 4

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 
2
4

If you want to check the presence of an element in the array, you can use include?:

if arr.include?(c)
  # do stuff
else 
  # don’t
end
2

Use Array#index for this:

c = 'c'
%w{a b c}.index(c)
3
  • I think you meant to write %w{a b c}
    – waldrumpus
    Sep 27, 2012 at 8:20
  • @waldrumpus Yes, thanks, copypasted from source in the question.
    – Hck
    Sep 27, 2012 at 8:52
  • So you did - sorry, I should have posted the comment above.
    – waldrumpus
    Sep 27, 2012 at 9:02
0
if arr.last == c
  # do some stuff
else
  # don't do some stuff
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.