是否有一种惯用的 ruby/rails 方法返回第一个真实的映射值?
我有一个对象数组,其中一些响应 :description,我想从第一个对象中获取真实描述的描述。我可以这样做:
objects.detect{|o| o.try(:description)}.description
或这样:
objects.map{|o| o.try(:description)}.detect{|o| o}
但第一个不是 DRY(描述在那里两次),第二个在找到值之前迭代整个数组。 ruby 标准库或 Rails 的扩展中是否有任何东西可以让我做这样的事情:
objects.detect_and_return{|o| o.try(:description)}
我知道我可以很容易地编写它,但标准库足够大,我可能不需要这样做。有没有像我的 detect_and_return
一样工作的函数?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我还没有见过这样的方法,我发现的最接近的是我在 gem
merb-cache
中找到的方法capture_first
。似乎他们偶然发现了同样的问题并实现了这个:您还可以看看 Array 和 Enumerable 方法facets 库,看看是否找到类似的内容。 Facets 包含很多好东西,所以你可能会很幸运。
I haven't seen such a method, and the closest I found was a method
capture_first
which I found in the gemmerb-cache
. Seems they stumbled on the same problem and implemented this: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.