find_index(*args) public

Returns the index of the first object in ary such that the object is

to obj.

If a block is given instead of an argument, returns the index of the first object for which the block returns true. Returns nil if no match is found.

See also Array#rindex.

An Enumerator is returned if neither a block nor argument is given.

a = [ "a", "b", "c" ]
a.index("b")              #=> 1
a.index("z")              #=> nil
a.index { |x| x == "b" }  #=> 1
Show source
Register or log in to add new notes.
July 8, 2009 - (<= v1_8_7_72)
5 thanks

Using block version in Ruby < 1.8.7

The block usage was added in 1.8.7, so to get the same functionality in an earlier version of Ruby, you need to utilize the find method.

Here is a quick example:

match = list.find { |l| l.owner == myself }
match_index = list.index(match)

If you do some gymnastics, you can have it on one line without extra variables:

match_index = list.index(list.find { |l| l.owner == myself })
September 27, 2013
1 thank

Using find_index to return first match. Profit!

This example shows how to use find_index to return a result as soon as the first occurrence of what you are looking for is found.

Code example

class Widget <, :profit); end

class WidgetManager
  def initialize(*widgets)
    @widgets = widgets
  def is_any_widget_profitable?
    @widgets.find_index { |w| w.profit > 0 }  # <== usage!

wm ='a', -100),'b', 200),'c', 300))
wm.is_any_widget_profitable?  # => 1
(wm.is_any_widget_profitable?) ? 'some profit' : 'all loss'  # => "some profit"

wm ='a', -100),'b', -200),'c', -300))
wm.is_any_widget_profitable?  # => nil
(wm.is_any_widget_profitable?) ? 'some profit' : 'all loss'  # => "all loss"