Ruby index array method

In ruby programming language , index(obj) method is takes an object parameter. When objects are exist in array this method returns index position of first occured object. Otherwise that returning a nil value. Which is indicate object are not exist in given array. Syntax of this method as follows.

index(obj) → int or nil
index {|i| block} → int or nil
index → Enumerator

index() array method example

In this section mentioning few examples. Which is based on index() method.

# Our array
record  = ["a", "b", "f", "e", "c", "f", "o"]
# Find index of given object
p1 = record.index('c')
p2 = record.index('f')
p3 = record.index('e')
p4 = record.index('u')

# Display record
print(record)
# Display position
print("\n",p1) # 4
print("\n",p2) # 2
print("\n",p3) # 3
print("\n",p4) # nil
Ruby index method example 1
["a", "b", "f", "e", "c", "f", "o"]
4
2
3
# Our array
record  = ["a", "b", "f", "e","f", "c", "f", "o"]

# Find index of given object
p1 = record.index{|x| x == "c"}
p2 = record.index("b")
p3 = record.index

# Display record
print(record)

# Display position
print("\n p1 : ",p1) # 4
print("\n p2 : ",p2) # 2
# Display the Enumerator value 
p3.each{|i|
  print("\n",i) 
}
["a", "b", "f", "e", "f", "c", "f", "o"]
 p1 : 5
 p2 : 1
a
b
f
e
f
c
f
o


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved