Ruby rindex array method

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

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

rindex() array method example

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

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

# Display record
print(record)
# Display position
print("\n",p1) # 4
print("\n",p2) # 6
print("\n",p3) # 5
print("\n",p4) # nil
Ruby rindex method example 1
["a", "b", "f", "e", "c", "e", "f", "o"]
4
6
5

The enumerator of this method print data from the backward direction. for example.

# Our array
record  = ["a", "b", "f", "e","f", "c", "f", "o"]

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

# 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
  o
  f
  c
  f
  e
  f
  b
  a


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