Ruby Array find_first object?

Dan Halabe picture Dan Halabe · Mar 4, 2010 · Viewed 108.5k times · Source

Am I missing something in the Array documentation? I have an array which contains up to one object satisfying a certain criterion. I'd like to efficiently find that object. The best idea I have from the docs is this:

candidates = my_array.select { |e| e.satisfies_condition? }
found_it = candidates.first if !candidates.empty?

But I am unsatisfied for two reasons:

  1. That select made me traverse the whole array, even though we could have bailed after the first hit.
  2. I needed a line of code (with a condition) to flatten the candidates.

Both operations are wasteful with foreknowledge that there's 0 or 1 satisfying objects.

What I'd like is something like:

array.find_first(block)

which returns nil or the first object for which the block evaluates to true, ending the traversal at that object.

Must I write this myself? All those other great methods in Array make me think it's there and I'm just not seeing it.

Answer

Mladen Jablanović picture Mladen Jablanović · Mar 4, 2010

Either I don't understand your question, or Enumerable#find is the thing you were looking for.