Menu
Coddy logo textTech

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? }    # false

any? is true when at least one does:

[1, 2, 3].any? { |n| n.even? }    # true
[1, 3, 5].any? { |n| n.even? }    # false

none? is true when none of them do:

[1, 3, 5].none? { |n| n.even? }   # true

The methods short-circuit, any? stops at the first match, all? stops at the first failure. They're cheap.

challenge icon

Challenge

Easy

Read 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 most 100
  • any? score is exactly 100 (at least one perfect score)
  • at least 3 scores are >= 70 (use count)

Print exactly one line:

  • Valid: <count> passing when all four conditions hold (count is the count of scores >= 70)
  • Invalid otherwise

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                   # 5

all? – true when every element satisfies the block:

[2, 4, 6].all? { |n| n.even? }  # true

any? – true when at least one element satisfies the block:

[1, 2, 3].any? { |n| n.even? }  # true

none? – true when no element satisfies the block:

[1, 3, 5].none? { |n| n.even? }  # true

These 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow