Finding the index of an item using a block

Posted Friday, April 18, 2008  

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 Arraydef 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 = sizereverse_each do |entry|
    index -= 1
    return index if yield(entry)
  end
  nil
end
alias_method :rindex_without_block, :rindex
alias_method :rindex, :rindex_with_blockend

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

Tweet This Delicious Reddit Stumble Upon Digg Share on Tumblr email

About Simon

Husband, Father, One-time Entrepreneur.

Aka Haruki Zaemon. Aka Sampy.

In my younger years I wanted to save the world; now I'm happy solving bigger problems than I create.

If I didn't need to work I'd be teaching Aikido and spending all my free time with my amazing wife and two children in Woodend, Victoria, Australia.

Books

Beginning Algorithms
with James Ross

Software

Simian
Similarity Analyser

Blog Categories