Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexOf in Ruby

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
like image 813
Jackie Chan Avatar asked Sep 27 '12 08:09

Jackie Chan


People also ask

What is index method in Ruby?

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()

How do you find the index in Ruby?

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.

What is array index in Ruby?

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.

How do you compare two arrays in Ruby?

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.


1 Answers

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 
like image 50
xdazz Avatar answered Oct 02 '22 17:10

xdazz