Array#find_index
allows you to find the index of the first item that either
object
, orArray#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?}
There are three different kinds of arrays: indexed arrays, multidimensional arrays, and associative arrays.
Answer: they're not! This happens because arrays passed into functions are always converted into pointers.
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.
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.
In Ruby 1.9.2 Array#rindex
accepts block: http://apidock.com/ruby/Array/rindex
Or you could do something like
last_index = array.map {|i| i.is_wanted? }.rindex(true)
which is a bit prettier
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With