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 # CBehind 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
EasyRead a comma-separated list of integer ages. For each age, classify it with a case statement using ranges:
0..12:Child13..19:Teen20..64:Adult65or 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: 1Cheat 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 # CTry it yourself
ages = gets.chomp.split(",").map(&:to_i)
# TODO: classify each age with case + ranges, count per category, print report
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