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
index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found. Syntax: str.index()
Ruby | Array class find_index() operation Array#find_index() : find_index() is a Array class method which returns the index of the first array. If a block is given instead of an argument, returns the index of the first object for which the block returns true.
Arrays are ordered, integer-indexed collections of any object. Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array—that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.
Ruby arrays may be compared using the ==, <=> and eql? methods. The == method returns true if two arrays contain the same number of elements and the same contents for each corresponding element.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With