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
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
arr
from you question, yes 'c'
is not in your array, "'c'"
does.
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
Use Array#index for this:
c = 'c'
%w{a b c}.index(c)