Take the 2-minute tour ×

I have an array of objects, some of which respond to :description, and I want to get the description from the first one with a truthy description. I could do this:

objects.detect{|o| o.try(:description)}.description

or this:

objects.map{|o| o.try(:description)}.detect{|o| o}

but the first isn't DRY (description is in there twice) and the second iterates through the whole array before finding the value. Is there anything in the ruby standard library, or in Rails' extensions to it, which would let me do something like this:

objects.detect_and_return{|o| o.try(:description)}

I know I could write it easily enough, but the standard libraries are big enough that I might not need to. Is there a function which works like my detect_and_return?

share|improve this question
Is there a functional programming term for this (apart from lazy evaluation)? –  Andrew Grimm Aug 14 '11 at 23:29
add comment

1 Answer

up vote 6 down vote accepted

I haven't seen such a method, and the closest I found was a method capture_first which I found in the gem merb-cache. Seems they stumbled on the same problem and implemented this:

module Enumerable
  def capture_first
    each do |o|
      return yield(o) || next

You could also take a look at the Array and Enumerable methods in the Ruby facets library and see if you find something similar. Facets contains quite a lot of goodies, so you might get lucky.

share|improve this answer
Indeed - Enumerable#find_yield, aka Enumerable#map_detect. Thanks - I'd not heard about facets before. –  Simon Aug 3 '11 at 13:45
add comment

Your Answer


