ruby picture

RCR 284: Let Array#index take a block

Submitted by flgr (Sun Oct 24 19:10:44 UTC 2004)

Abstract

I think it is a frequent task to find the index of an element of an Array that matches a specific condition. Currently this can only be done easily in two passes.

Problem

Array.index() can currently only compare Objects directly, but finding the index where a condition that is not only a simple object equality check has currently to be done manually. This is for example a problem when trying to find the index of a Float:


    
  items = [1.5, 4.9, 1.3, 8.4]
  items.index(2.2 - 0.7) # => nil
  items.find_all { |item| (item - (2.2 - 0.7)).abs < 1e-10 }.map { |item| items.index(item) } # => [0]

  

Proposal

I think it should be possible to express this like this:


    
  items.index { |item| (item - (2.2 - 0.7)).abs < 1e-10 } # => [0]

  

Analysis

It can be argued over whether this should return an Array of indices or only the first matching index.

The direct object comparisation form of Array#index currently only returns the first result, but with blocks I think it is more useful to return all of them.

Implementation

In Ruby: (Note that this doesn't give the correct indices if multiple matching elements are equal and that it doesn't give you a performance advantage)


    
  class Array
    alias :old_index :index
  def index(*args, &block)
      if not args.empty?
        old_index(*args)
      else
        result = find_all(&block).map { |item| old_index(item) }
        return nil if result.empty?
        return result
      end
    end
  end

    

ruby picture
Comments Current voting

Just wanted to thank you for taking the time to RCR this. I too suggested it on ruby-talk a bit ago, and I'm sure it's been suggested before, probably by you. It's an obvious use case, so I have little doubt, this should be approved. --T.


I voted neutral. There seems to be a compelling case, but the way it's demonstrated here doesn't excite me, probably because of the ambiguity of the return value. A singular noun (index) returning multiple values is a bit strange. --GavinSinclair


this is needed!


Strongly opposed 0
Opposed 0
Neutral 1
In favor 1
Strongly advocate 1
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .