Is there an equivalent of Array#find_index for the last index in ruby?

Viewed 14639

Array#find_index allows you to find the index of the first item that either

  • is equal to an object, or
  • makes a block passed to it evaluate to true

Array#rindex can allow you to find the index of the last item that is equal to an object, but is there anything that allows you to find the index of the last item that makes a block passed to it return true?

Otherwise, should I do something like

last_index = array.length - 1 - array.reverse.find_index{|item| item.is_wanted?}
6 Answers

First and Last index number can be identified in the following way:

for Integer Array:

irb(main):003:0> month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
=> [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
irb(main):004:0> puts month.first
31
=> nil
irb(main):005:0> puts month.last
31
=> nil
irb(main):006:0> puts month.index(month.first)
0
=> nil
irb(main):007:0> puts month.rindex(month.last)
11
=> nil
irb(main):008:0>

for String Array:

irb(main):013:0> weekDays = Array[ "Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun" ]
=> ["Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun"]
irb(main):014:0> puts weekDays.first
Mon
=> nil
irb(main):015:0> puts weekDays.last
Sun
=> nil
irb(main):016:0> puts weekDays.index(weekDays.first)
0
=> nil
irb(main):017:0> puts weekDays.rindex(weekDays.last)
6
=> nil
irb(main):018:0>

array.index(element) also can identify the last index number if there is no duplicate/copy element in the array. But I think that it is better to use array.rindex(element) to find out last index number. Originally array.rindex(element) is created to identify the last index number of the similar elements given in an array. For more info: https://rubyapi.org/2.7/o/array#method-i-rindex

Related