Ruby case Statement

Handle multiple conditions elegantly

🎯 What is a case Statement?

The case statement provides a clean way to compare a value against multiple conditions. It's more readable than multiple elsif statements and perfect for handling many possible values, like menu selections or status codes.


day = "Monday"

case day
when "Monday"
  puts "Start of the week"
when "Friday"
  puts "Almost weekend!"
else
  puts "Midweek day"
end
# Output: Start of the week
                                    

Output:

Start of the week

case Statement Concepts

🎲

Basic case

Match single values

case grade
when "A"
  puts "Excellent"
end
📋

Multiple Values

Match several values at once

case day
when "Sat", "Sun"
  puts "Weekend"
end
📊

Range Matching

Match ranges of values

case score
when 90..100
  puts "A grade"
end
🔄

else Clause

Default case for no match

case value
when 1
  puts "One"
else
  puts "Other"
end

🔹 Basic case Statement

The case statement compares a value against multiple when clauses. When a match is found, that code block executes and the case statement ends. This is cleaner than writing many elsif statements and makes your code easier to read and maintain.

# Simple case statement
grade = "B"

case grade
when "A"
  puts "Excellent!"
when "B"
  puts "Good job!"
when "C"
  puts "Satisfactory"
when "D"
  puts "Needs improvement"
when "F"
  puts "Failed"
else
  puts "Invalid grade"
end
# Output: Good job!

# Another example
traffic_light = "red"

case traffic_light
when "green"
  puts "Go"
when "yellow"
  puts "Slow down"
when "red"
  puts "Stop"
end
# Output: Stop
                            

Output:

Good job!

Stop

🔹 Multiple Values in when

You can match multiple values in a single when clause by separating them with commas. This is useful when different values should trigger the same action, like grouping weekdays together or handling similar status codes with one response.

# Multiple values in one when
day = "Saturday"

case day
when "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
  puts "It's a weekday"
when "Saturday", "Sunday"
  puts "It's the weekend!"
end
# Output: It's the weekend!

# Another example
month = "December"

case month
when "December", "January", "February"
  puts "Winter season"
when "March", "April", "May"
  puts "Spring season"
when "June", "July", "August"
  puts "Summer season"
when "September", "October", "November"
  puts "Fall season"
end
# Output: Winter season
                            

Output:

It's the weekend!

Winter season

🔹 case with Ranges

Case statements can match ranges, making them perfect for categorizing numeric values. Use ranges in when clauses to check if a value falls within a specific interval, like grading scores or age groups. Ruby checks ranges using the === operator.

# Using ranges in case
score = 85

case score
when 90..100
  puts "Grade: A"
when 80..89
  puts "Grade: B"
when 70..79
  puts "Grade: C"
when 60..69
  puts "Grade: D"
else
  puts "Grade: F"
end
# Output: Grade: B

# Age categories
age = 35

case age
when 0..12
  puts "Child"
when 13..19
  puts "Teenager"
when 20..59
  puts "Adult"
when 60..120
  puts "Senior"
else
  puts "Invalid age"
end
# Output: Adult
                            

Output:

Grade: B

Adult

🔹 case with Return Values

Case statements return the value of the executed when clause, allowing you to assign the result directly to a variable. This makes code more concise by eliminating the need for separate assignment statements in each branch.

# Assigning case result to variable
day = "Wednesday"

day_type = case day
when "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
  "Weekday"
when "Saturday", "Sunday"
  "Weekend"
else
  "Unknown"
end

puts day_type  # Output: Weekday

# Another example
temperature = 28

weather = case temperature
when 0..10
  "Cold"
when 11..20
  "Cool"
when 21..30
  "Warm"
else
  "Hot"
end

puts "It's #{weather} today"  # Output: It's Warm today
                            

Output:

Weekday

It's Warm today

🔹 case without an Argument

You can use case without specifying a value to compare, making it work like a series of if-elsif statements. Each when clause contains its own condition, providing flexibility for complex logic where different conditions need different comparisons.

# case without argument
score = 75
attendance = 85

result = case
when score >= 90 && attendance >= 90
  "Excellent"
when score >= 80 && attendance >= 80
  "Very Good"
when score >= 70 && attendance >= 70
  "Good"
when score >= 60
  "Pass"
else
  "Fail"
end

puts result  # Output: Good

# Another example
time = 14

greeting = case
when time < 12
  "Good morning"
when time < 18
  "Good afternoon"
else
  "Good evening"
end

puts greeting  # Output: Good afternoon
                            

Output:

Good

Good afternoon

🔹 Practical case Examples

Case statements shine in real-world scenarios like menu systems, status handlers, and type checkers. They make code more organized and easier to extend when you need to add new options. Here are common patterns you'll use frequently in Ruby applications.

# Menu system
choice = 2

case choice
when 1
  puts "Starting new game..."
when 2
  puts "Loading saved game..."
when 3
  puts "Opening settings..."
when 4
  puts "Exiting game..."
else
  puts "Invalid choice"
end
# Output: Loading saved game...

# HTTP status codes
status_code = 404

message = case status_code
when 200
  "OK"
when 404
  "Not Found"
when 500
  "Internal Server Error"
else
  "Unknown Status"
end

puts message  # Output: Not Found

# Type checking
value = "hello"

case value
when String
  puts "It's a string"
when Integer
  puts "It's a number"
when Array
  puts "It's an array"
else
  puts "Unknown type"
end
# Output: It's a string
                            

Output:

Loading saved game...

Not Found

It's a string

🧠 Test Your Knowledge

What is the advantage of case over multiple elsif statements?