Bird
Raised Fist0
Rubyprogramming~10 mins

Case/when statement in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Case/when statement
Start
↓
Evaluate expression
↓
Compare with when conditions
↓
Match found?
No→Else block or nil
↓
Execute matched block
↓
End
The case expression evaluates once, then compares to each when condition until a match is found, executing that block or else block if no match.
Execution Sample
Ruby
grade = 'B'
case grade
when 'A'
  puts 'Excellent'
when 'B'
  puts 'Good'
else
  puts 'Needs Improvement'
end
This code checks the value of grade and prints a message based on its value.
Execution Table
StepExpression ValueWhen ConditionMatch?ActionOutput
1'B''A'NoCheck next when
2'B''B'YesExecute puts 'Good'Good
3N/AN/AN/AExit case
💡 Match found at step 2, so case ends after executing that block.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
gradenil'B''B''B'
Key Moments - 2 Insights
Why does the case statement stop checking after the first match?
Because once a when condition matches the expression value (see step 2 in execution_table), Ruby executes that block and exits the case immediately.
What happens if no when condition matches and there is no else block?
The case expression returns nil and no code inside case runs, as no match was found and no else block exists.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 2?
AGood
BExcellent
CNeeds Improvement
DNo output
💡 Hint
Check the 'Output' column at step 2 in the execution_table.
At which step does the case statement find a match?
AStep 1
BStep 2
CStep 3
DNo match found
💡 Hint
Look at the 'Match?' column in the execution_table.
If grade was 'C' and no else block was present, what would happen?
AIt would print 'Needs Improvement'
BIt would print 'Good'
CIt would print nothing and return nil
DIt would cause an error
💡 Hint
Refer to key_moments about no match and no else block behavior.
Concept Snapshot
case expression
case variable
when value1
  # code if match
when value2
  # code if match
else
  # code if no match
end

Evaluates variable once, compares to when values, runs first matching block or else block.
Full Transcript
The case/when statement in Ruby evaluates an expression once and compares it to each when condition in order. If a match is found, it executes that block and exits the case. If no match is found, it runs the else block if present, otherwise returns nil. In the example, grade is 'B'. The case checks 'A' first (no match), then 'B' (match), so it prints 'Good' and stops. This prevents checking further conditions after a match. If no when matches and no else exists, nothing runs and nil is returned.

Practice

(1/5)
1.

What does the case/when statement do in Ruby?

easy
A. It chooses which code to run based on matching a value.
B. It repeats code multiple times.
C. It defines a new method.
D. It creates a new variable.

Solution

  1. Step 1: Understand the purpose of case/when

    The case/when statement compares a value to different options to decide which code to run.
  2. Step 2: Compare with other options

    Repeating code is done by loops, defining methods uses def, and variables are created by assignment, so these are incorrect.
  3. Final Answer:

    It chooses which code to run based on matching a value. -> Option A
  4. Quick Check:

    case/when selects code by value match [OK]
Hint: Remember: case/when picks code by matching values [OK]
Common Mistakes:
  • Confusing case/when with loops
  • Thinking case/when defines methods
  • Believing case/when creates variables
2.

Which of the following is the correct syntax for a case/when statement in Ruby?

case x
  when 1
    puts "One"
  when 2
    puts "Two"
  else
    puts "Other"
end
easy
A. case x when 1 puts "One" when 2 puts "Two" else puts "Other" end
B. case x { when 1: puts "One" when 2: puts "Two" else: puts "Other" }
C. switch(x) { case 1: puts "One" case 2: puts "Two" default: puts "Other" }
D. if x == 1 then puts "One" elsif x == 2 then puts "Two" else puts "Other" end

Solution

  1. Step 1: Check Ruby case/when syntax

    Ruby uses case followed by when clauses and ends with end. No braces or colons are used.
  2. Step 2: Compare options

    case x when 1 puts "One" when 2 puts "Two" else puts "Other" end matches Ruby syntax exactly. Options B and C use braces and colons like other languages. if x == 1 then puts "One" elsif x == 2 then puts "Two" else puts "Other" end is an if/elsif, not case/when.
  3. Final Answer:

    case x when 1 puts "One" when 2 puts "Two" else puts "Other" end -> Option A
  4. Quick Check:

    Ruby case/when uses no braces or colons [OK]
Hint: Ruby case/when uses no braces or colons, just end [OK]
Common Mistakes:
  • Using braces or colons like other languages
  • Confusing case/when with switch/case from other languages
  • Using if/elsif instead of case/when
3.

What is the output of this Ruby code?

grade = 'B'
case grade
when 'A'
  puts "Excellent"
when 'B', 'C'
  puts "Good"
when 'D'
  puts "Pass"
else
  puts "Fail"
end
medium
A. Fail
B. Excellent
C. Pass
D. Good

Solution

  1. Step 1: Identify the value of grade

    The variable grade is set to 'B'.
  2. Step 2: Match grade in case/when

    The when 'B', 'C' line matches 'B', so it runs puts "Good".
  3. Final Answer:

    Good -> Option D
  4. Quick Check:

    grade 'B' matches when 'B', 'C' [OK]
Hint: Check all values in when line, including multiple matches [OK]
Common Mistakes:
  • Only checking first value in when list
  • Confusing else output
  • Ignoring multiple values in one when
4.

Find the error in this Ruby code snippet:

score = 85
case score
when 90..100
  puts "A"
when 80..89
  puts "B"
when 70..79
  puts "C"
else
  puts "F"
end

Why does it not print "B" for score 85?

medium
A. Ranges in when must be strings, not numbers.
B. The case statement compares score with ranges incorrectly; use case with when and ===.
C. The code is correct; it will print "B" as expected.
D. The ranges overlap and cause confusion.

Solution

  1. Step 1: Understand how case/when works with ranges

    Ruby's case/when uses the === operator, which works with ranges to check if a value is inside.
  2. Step 2: Check the given score and ranges

    Score 85 falls inside 80..89, so puts "B" will run correctly.
  3. Final Answer:

    The code is correct; it will print "B" as expected. -> Option C
  4. Quick Check:

    Ranges work with case/when using === [OK]
Hint: Ranges work naturally in when clauses with case [OK]
Common Mistakes:
  • Thinking ranges must be strings
  • Believing case/when can't handle ranges
  • Assuming overlapping ranges cause errors here
5.

You want to write a Ruby case/when statement that prints "Weekend" for Saturday and Sunday, "Weekday" for Monday to Friday, and "Invalid" for any other input. Which code correctly does this?

hard
A. case day when 'Saturday', 'Sunday' puts "Weekend" when 'Monday'..'Friday' puts "Weekday" else puts "Invalid" end
B. case day when 'Saturday', 'Sunday' puts "Weekend" when 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' puts "Weekday" else puts "Invalid" end
C. case day when 'Saturday'..'Sunday' puts "Weekend" when 'Monday'..'Friday' puts "Weekday" else puts "Invalid" end
D. case day when ['Saturday', 'Sunday'] puts "Weekend" when ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] puts "Weekday" else puts "Invalid" end

Solution

  1. Step 1: Understand how to list multiple values in when

    Use commas to separate multiple values in one when line, like when 'Saturday', 'Sunday'.
  2. Step 2: Check each option

    case day when 'Saturday', 'Sunday' puts "Weekend" when 'Monday'..'Friday' puts "Weekday" else puts "Invalid" end incorrectly uses a range of strings 'Monday'..'Friday' which does not work as expected for days. case day when ['Saturday', 'Sunday'] puts "Weekend" when ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] puts "Weekday" else puts "Invalid" end uses arrays in when, which does not match values correctly. case day when 'Saturday'..'Sunday' puts "Weekend" when 'Monday'..'Friday' puts "Weekday" else puts "Invalid" end uses string ranges like 'Saturday'..'Sunday' which is not meaningful for days. case day when 'Saturday', 'Sunday' puts "Weekend" when 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' puts "Weekday" else puts "Invalid" end correctly lists each weekday separately with commas.
  3. Final Answer:

    case day when 'Saturday', 'Sunday' puts "Weekend" when 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday' puts "Weekday" else puts "Invalid" end -> Option B
  4. Quick Check:

    Use commas for multiple values in when [OK]
Hint: Use commas, not ranges or arrays, for multiple when values [OK]
Common Mistakes:
  • Using ranges of strings for days
  • Using arrays inside when clauses
  • Trying to use string ranges that don't work
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard