开发者

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

开发者 https://www.devze.com 2023-03-24 17:43 出处:网络
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:

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 r开发者_运维知识库uby 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消