0
0
Rubyprogramming~10 mins

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

Choose your learning style9 modes available
Concept Flow - Case/when statement
Start
Evaluate expression
Compare with when conditions
Match found?
NoElse 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.