简体   繁体   中英

How do I get the first element upon certain condition in an Enumerator?

I have:

a = [1,2,3,4,5,4,3,2,1]
a.select{|x| x > 3} #=> [4, 5, 4]

What I want is "4", the first element that applies to the condition only. I know I could do:

a.select{|x| x > 3}.first #=> 4

But is this my best option? The select method will go trough all elements. Is there a more efficient way to apply this?

Here it is using Enumerable#find :

a = [1,2,3,4,5,4,3,2,1]
a.find{|x| x > 3}
# => 4

使用find而不是select

a.find { |x| x > 3 } # => 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM