Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ruby

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?}
like image 880
Andrew Grimm Avatar asked Aug 24 '10 06:08

Andrew Grimm


People also ask

What are the 3 types of arrays?

There are three different kinds of arrays: indexed arrays, multidimensional arrays, and associative arrays.

Can a pointer equal to an array?

Answer: they're not! This happens because arrays passed into functions are always converted into pointers.

What is the correct definition of array?

5a(1) : a number of mathematical elements arranged in rows and columns. (2) : a data structure in which similar elements of data are arranged in a table. b : a series of statistical data arranged in classes in order of magnitude. 6 : a group of elements forming a complete unit an antenna array.

Are two arrays equal?

Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.


3 Answers

In Ruby 1.9.2 Array#rindex accepts block: http://apidock.com/ruby/Array/rindex

like image 78
Nakilon Avatar answered Sep 24 '22 22:09

Nakilon


Or you could do something like

last_index = array.map {|i| i.is_wanted? }.rindex(true)

which is a bit prettier

like image 45
telent Avatar answered Sep 22 '22 22:09

telent


Such a shame it comes until 1.9.2. In the meantime, if you don't want to reverse your array, but rather enumerate the search in reverse, you can do

last_index = array.length - 1 - array.rindex.find_index{|item| item.is_wanted? } (1.8.7 and up)

like image 22
Chubas Avatar answered Sep 23 '22 22:09

Chubas