count, all?, any?, none?
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 24 of 56.
Four small Enumerable methods that answer questions about a collection without forcing you to write a loop.
count returns how many elements satisfy the block:
[1, 2, 3, 4, 5].count { |n| n.even? } # 2
[1, 2, 3, 4, 5].count # 5 (no block, total count)all? is true when every element satisfies the block:
[2, 4, 6].all? { |n| n.even? } # true
[2, 4, 7].all? { |n| n.even? } # falseany? is true when at least one does:
[1, 2, 3].any? { |n| n.even? } # true
[1, 3, 5].any? { |n| n.even? } # falsenone? is true when none of them do:
[1, 3, 5].none? { |n| n.even? } # trueThe methods short-circuit, any? stops at the first match, all? stops at the first failure. They're cheap.
Challenge
EasyRead a comma-separated list of test scores (integers). A class is a valid passing class when:
none?of the scores is negative (an unrecorded test)all?scores are at most100any?score is exactly100(at least one perfect score)- at least 3 scores are
>= 70(usecount)
Print exactly one line:
Valid: <count> passingwhen all four conditions hold (countis the count of scores>= 70)Invalidotherwise
For input 72,80,100,65,90: 4 scores >= 70, none negative, all <= 100, one is 100, so the output is Valid: 4 passing.
For 72,80,90: 3 passing but no perfect score, so Invalid.
Cheat sheet
Four Enumerable methods that answer questions about a collection:
count – returns how many elements satisfy the block (or total size without a block):
[1, 2, 3, 4, 5].count { |n| n.even? } # 2
[1, 2, 3, 4, 5].count # 5all? – true when every element satisfies the block:
[2, 4, 6].all? { |n| n.even? } # trueany? – true when at least one element satisfies the block:
[1, 2, 3].any? { |n| n.even? } # truenone? – true when no element satisfies the block:
[1, 3, 5].none? { |n| n.even? } # trueThese methods short-circuit: any? stops at the first match, all? stops at the first failure.
Try it yourself
scores = gets.chomp.split(",").map(&:to_i)
# TODO: combine all?, any?, none?, count to decide Valid vs Invalid
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier