Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an idiomatic ruby/rails way of returning the first truthy mapped value?

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?

like image 597
Simon Avatar asked Aug 03 '11 12:08

Simon


1 Answers

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
    end
    nil
  end
end

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.

like image 73
Casper Avatar answered Nov 15 '22 21:11

Casper