« It's OK for GET Requests to Update the Database | Main | HTTP Ranges for Pagination? »

Finding the index of an item using a block

Listen to this articleListen to this article

Update: Ruby 1.8.7 also has this.

Ruby 1.9 has it but if you're not that bleeding edge, you can have it now:

class Array
  def index_with_block(*args)
    return index_without_block(*args) unless block_given?
    each_with_index do |entry, index|
      return index if yield(entry)
    end
    nil
  end
  alias_method :index_without_block, :index
  alias_method :index, :index_with_block

  def rindex_with_block(*args)
    return rindex_without_block(*args) unless block_given?
    
    index = size
    reverse_each do |entry|
      index -= 1
      return index if yield(entry)
    end
    nil
  end
  alias_method :rindex_without_block, :rindex
  alias_method :rindex, :rindex_with_block
end

If you're using Rails you can substitute the two calls each to alias_method with a single call to alias_method_chain.

Post a comment