Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is array.index() in Ruby?

okwudili onyejiaku

array.index() is a method in Ruby that returns the index position of the specified element in the array.

Syntax

array.index(elem)

Parameters

  • elem: The array element whose index is to be determined.

Return value

The index() method returns the index of the first instance of the specified element.

Code

Example 1

In the example below, we shall create some arrays and use the index() method.

# create Ruby arrays
array1 = [1, 2, 3, 4, 5, 4]
array2 = ["a", "b", "c", "d", "e"]
array3 = ["Python", "Django", "Flask"]
array4 = [true, false, nil]
array5 = [["abc", "def"], 20, 30,40]

# find index of some elements or objects
a = array1.index(4)         # return index of 4
b = array2.index("a")       # return index of "a"
c = array3.index("Flask")   # return index of "Flask"
d = array4.index(false)       # return index of false
e = array5.index(40)        # return index of 40

# print returned values
puts a
puts b
puts c
puts d
puts e

In the code above, the indices of the specified array elements are returned. In array1 where 4 occurs twice, the index of its first instance is returned.

Example 2

Note that either nothing or nil is returned when the element whose index is to be determined does not exist in the array.

# create new array
array = [1, 2, 3, 4, 5]

# return the index of 10
a = array.index(10)   # nothing is returned

# print returned value
puts a   # nothing is printed

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring