Donato Donato - 4 months ago 7
Ruby Question

get all truthy values in an array within a given limit

I want to get all truthy values in an array (in this example that would be numeric values). But once the limit has been reached I do not want to continue looking for truthy values. My initial thought was to do this:

a.select do |n|
puts "value #{n}"
n.is_a? Numeric
end.slice(0..9)

value 1
value 2
value 3
value 4
value 5
value 6
value 7
value 8
value 9
value 10
value 11
value 12
value 13
value 14
value 15
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


While it gives me the correct results, it still searches through every record. I want it to stop searching when I hit the limit.

How can I achieve this in Ruby?

Answer

This could be achieved with lazy and first - both methods are defined on Enumerable:

(1..20).lazy.select do |n|
  puts "value #{n}"
  n.is_a? Numeric
end.first(10)
#=> value 1
#=> value 2
#=> value 3
#=> value 4
#=> value 5
#=> value 6
#=> value 7
#=> value 8
#=> value 9
#=> value 10
#=> [1,2,3,4,5,6,7,8,9,10]