This tutorial will teach you how to use Ruby’s `case/when` control structure effectively. You’ll learn its syntax, practical applications, and how to solve real-world problems using this powerful tool.
Step 1: Introduction to `case/when`
The case/when statement in Ruby is a powerful alternative to multiple if/elsif conditions. It allows you to compare a value against multiple patterns and execute code based on the first match. It's clean, readable, and efficient.
day = 'Monday'
case day
when 'Monday'
puts 'Start of the work week!'
when 'Friday'
puts 'Almost the weekend!'
else
puts 'Just another day.'
endPractice Exercise
Write a case/when statement that checks the value of a variable weather and prints a message based on whether it's 'sunny', 'rainy', or 'cloudy'.
Show Solution
weather = 'sunny'
case weather
when 'sunny'
puts 'Wear sunscreen and enjoy the day!'
when 'rainy'
puts 'Don't forget your umbrella!'
when 'cloudy'
puts 'A jacket might be a good idea.'
else
puts 'Check the weather forecast!'
endStep 2: Using Ranges in `case/when`
You can use ranges (e.g., 1..10) in when clauses to match a range of values. This is useful for categorizing numeric data or grouping similar conditions.
age = 25
case age
when 0..12
puts 'Child'
when 13..19
puts 'Teenager'
when 20..60
puts 'Adult'
else
puts 'Senior'
endPractice Exercise
Write a case/when statement that categorizes a temperature variable into 'freezing' (below 0), 'cold' (0-15), 'moderate' (16-25), and 'hot' (above 25).
Show Solution
temperature = 10
case temperature
when -Float::INFINITY..0
puts 'Freezing! Bundle up.'
when 0..15
puts 'Cold. Wear a jacket.'
when 16..25
puts 'Moderate. Perfect weather!'
else
puts 'Hot. Stay hydrated!'
endStep 3: Using Regular Expressions in `case/when`
Ruby allows you to use regular expressions in when clauses. This is particularly useful for matching strings against patterns.
email = 'user@example.com'
case email
when /@gmail.com$/
puts 'Gmail user'
when /@yahoo.com$/
puts 'Yahoo user'
else
puts 'Other email provider'
endPractice Exercise
Write a case/when statement that checks if a phone_number variable matches a valid US phone number format (e.g., (123) 456-7890).
Show Solution
phone_number = '(123) 456-7890'
case phone_number
when /\(\d{3}\) \d{3}-\d{4}/
puts 'Valid US phone number.'
else
puts 'Invalid phone number format.'
endStep 4: Combining Conditions with `when`
You can combine multiple conditions in a single when clause using the && or || operators. This allows for more complex logic within a case statement.
age = 25
income = 50000
case
when age >= 18 && income > 40000
puts 'Eligible for a premium credit card.'
when age >= 18 && income <= 40000
puts 'Eligible for a standard credit card.'
else
puts 'Not eligible for a credit card.'
endPractice Exercise
Write a case/when statement that checks if a user is eligible for a discount based on their age (must be over 60) or membership_status (must be 'premium').
Show Solution
age = 65
membership_status = 'premium'
case
when age > 60 || membership_status == 'premium'
puts 'Eligible for a discount!'
else
puts 'Not eligible for a discount.'
endStep 5: Using `case/when` with Objects
The case/when statement can also be used with objects and custom classes. Ruby uses the === operator to compare objects, which can be overridden for custom behavior.
class Animal
attr_reader :type
def initialize(type)
@type = type
end
def ===(other)
type == other.type
end
end
animal = Animal.new('dog')
case animal
when Animal.new('cat')
puts 'It's a cat!'
when Animal.new('dog')
puts 'It's a dog!'
else
puts 'Unknown animal.'
endPractice Exercise
Create a Vehicle class with a type attribute. Write a case/when statement that checks the type of a vehicle object and prints a message based on whether it's a 'car', 'bike', or 'truck'.
Show Solution
class Vehicle
attr_reader :type
def initialize(type)
@type = type
end
def ===(other)
type == other.type
end
end
vehicle = Vehicle.new('car')
case vehicle
when Vehicle.new('car')
puts 'It's a car!'
when Vehicle.new('bike')
puts 'It's a bike!'
when Vehicle.new('truck')
puts 'It's a truck!'
else
puts 'Unknown vehicle.'
endStep 6: Advanced: Nested `case/when` Statements
You can nest case/when statements to handle more complex decision-making scenarios. This is useful when you need to evaluate multiple conditions in a hierarchical manner.
age = 25
income = 50000
case age
when 18..30
case income
when 0..30000
puts 'Young adult with low income.'
when 30001..60000
puts 'Young adult with moderate income.'
else
puts 'Young adult with high income.'
end
when 31..60
puts 'Middle-aged adult.'
else
puts 'Senior citizen.'
endPractice Exercise
Write a nested case/when statement that categorizes a person based on their age and education_level (e.g., 'high school', 'college', 'graduate').
Show Solution
age = 22
education_level = 'college'
case age
when 18..22
case education_level
when 'high school'
puts 'High school student or recent graduate.'
when 'college'
puts 'College student.'
else
puts 'Young adult with advanced education.'
end
when 23..30
puts 'Young professional.'
else
puts 'Experienced professional.'
endStep 7: Real-World Application: Menu Selection
The case/when statement is often used in real-world applications like menu selection systems. It provides a clean way to handle user input and execute corresponding actions.
puts 'Welcome! Choose an option: 1. Check balance 2. Deposit 3. Withdraw'
option = gets.chomp.to_i
case option
when 1
puts 'Your balance is $1000.'
when 2
puts 'How much would you like to deposit?'
when 3
puts 'How much would you like to withdraw?'
else
puts 'Invalid option.'
endPractice Exercise
Create a simple menu system for a library. The user should be able to choose between '1. Borrow a book', '2. Return a book', and '3. Check available books'. Use case/when to handle the user's choice.
Show Solution
puts 'Welcome to the library! Choose an option: 1. Borrow a book 2. Return a book 3. Check available books'
option = gets.chomp.to_i
case option
when 1
puts 'Which book would you like to borrow?'
when 2
puts 'Which book are you returning?'
when 3
puts 'Available books: Ruby Programming, Clean Code, Design Patterns'
else
puts 'Invalid option.'
endStep 8: Best Practices and Tips
- Use
case/whenfor readability when comparing a single variable against multiple values. 2. Avoid overly complex nestedcase/whenstatements. 3. Use ranges and regular expressions to simplify conditions. 4. Always include anelseclause to handle unexpected cases.
Practice Exercise
Refactor the following if/elsif statement into a case/when statement:
if age < 13
puts 'Child'
elsif age < 20
puts 'Teenager'
elsif age < 65
puts 'Adult'
else
puts 'Senior'
endShow Solution
case age
when 0..12
puts 'Child'
when 13..19
puts 'Teenager'
when 20..64
puts 'Adult'
else
puts 'Senior'
endSign in to take Cornell notes on this lesson — they save automatically and stay with your account.