Enumerable queries in Ruby
all?, any?, none? and count: questions a collection answers itself.
temps = [61, 68, 72, 75, 66]
puts temps.all? { |t| t > 50 }
puts temps.any? { |t| t > 74 }
puts temps.none? { |t| t > 90 }
puts temps.count { |t| t.between?(65, 75) }
words = %w[stone brick straw]
puts words.all? { |w| w.length >= 5 }
puts words.find_index { |w| w.start_with?("s") }
puts words.sum(&:length)
How it works
all?,any?andnone?test the block across every element.countwith a block counts matches instead of everything.find_indexlocates the first match;sum(&:length)maps then adds.
Keywords and builtins used here
puts
The run, in numbers
- Lines
- 11
- Characters to type
- 310
- Tokens
- 111
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 83 seconds.
Step 3 of 3 in Enumerable, step 15 of 29 in Language basics.