typestar

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

  1. all?, any? and none? test the block across every element.
  2. count with a block counts matches instead of everything.
  3. find_index locates the first match; sum(&:length) maps then adds.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Enumerable, step 15 of 29 in Language basics.

← Previous Next →