Menu
Coddy logo textTech

Ranges in Case / When

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 8 of 56.

Ranges shine inside Ruby's case statement. Where many languages need a chain of if/elsif with comparison operators, Ruby lets you match a value against ranges directly.

score = 78
grade = case score
        when 90..100 then "A"
        when 80..89  then "B"
        when 70..79  then "C"
        when 60..69  then "D"
        else              "F"
        end
puts grade  # C

Behind the scenes, when 70..79 uses the range's === operator, which is equivalent to (70..79).include?(score).

The case form is shorter, easier to read, and faster to write than a long if/elsif ladder.

challenge icon

Challenge

Easy

Read a comma-separated list of integer ages. For each age, classify it with a case statement using ranges:

  • 0..12: Child
  • 13..19: Teen
  • 20..64: Adult
  • 65 or higher: Senior
  • Anything else (negative): skipped, doesn't go in the report

Print a count line for each non-zero category, in this fixed order: Child, Teen, Adult, Senior. Skip categories with zero people. After the counts, print Skipped: <n> where n is the number of negative (invalid) ages.

For input 5,15,30,70,-3,40,12, the output is:

Child: 2
Teen: 1
Adult: 2
Senior: 1
Skipped: 1

Cheat sheet

Use ranges in case statements — Ruby matches via === (equivalent to include?):

score = 78
grade = case score
        when 90..100 then "A"
        when 80..89  then "B"
        when 70..79  then "C"
        when 60..69  then "D"
        else              "F"
        end
puts grade  # C

Try it yourself

ages = gets.chomp.split(",").map(&:to_i)

# TODO: classify each age with case + ranges, count per category, print report
quiz iconTest yourself

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

All lessons in Logic & Flow