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.