Question
How do I write a switch statement in Ruby?
In languages such as JavaScript, Java, or C, this is often done with a switch statement. In Ruby, what is the equivalent way to compare a value against multiple possible cases and run different code depending on which case matches?
Short Answer
By the end of this page, you will understand how Ruby handles switch-style branching using case, when, and else. You will see the basic syntax, how matching works, how execution flows, where this pattern is useful in real programs, and the most common mistakes beginners make.
Concept
Ruby does not have a switch keyword like some other languages. Instead, it uses a case expression.
A case expression lets you compare one value against several possible matches and choose the first matching branch.
Basic idea:
case value
when option1
# code
when option2
# code
else
# fallback code
end
This is Ruby's equivalent of a switch statement.
Why it matters
When your program needs to choose between many known values, writing a long chain of if/elsif statements can become hard to read. A case expression makes that logic cleaner.
For example, you might use it to:
- handle menu choices
- respond to status values
- map user roles to permissions
- convert short codes into readable labels
Important Ruby detail
Ruby's case is more flexible than a traditional switch statement. It is often used for exact value matching, but it can also match ranges, classes, patterns, and other objects depending on how === works.
For beginners, the most important use is simple value matching.
Mental Model
Think of case like a receptionist checking a guest list.
- The receptionist looks at one name:
case value - Then checks each list entry:
when ... - As soon as a match is found, the correct action is taken
- If no match is found, the fallback action happens:
else
So instead of asking many separate questions like:
- Is it this?
- Is it this?
- Is it this?
Ruby says:
- Here is the value
- Compare it against these options in order
- Stop at the first match
That is why case is often easier to read than many elsif conditions.
Syntax and Examples
Basic syntax
case variable
when value1
# code for value1
when value2
# code for value2
else
# code if nothing matches
end
Example: matching a number
score = 2
case score
when 1
puts "Beginner"
when 2
puts "Intermediate"
when 3
puts "Advanced"
else
puts "Unknown level"
end
What this does
- Ruby reads
score - It compares
scorewith eachwhenvalue - Since
scoreis2, it runsputs "Intermediate" - The rest of the branches are skipped
Example: multiple values in one
Step by Step Execution
Consider this code:
fruit = "apple"
case fruit
when "banana"
puts "Yellow"
when "apple"
puts "Red or green"
else
puts "Unknown fruit"
end
Step-by-step
- Ruby sets
fruitto"apple". - Ruby starts the
case fruitexpression. - It checks the first branch:
when "banana". "apple"does not match"banana", so Ruby moves on.- It checks the next branch:
when "apple". - This matches.
- Ruby runs:
puts "Red or green"
- Ruby stops checking further branches.
- The
elsebranch is ignored because a match was already found.
Output
Real World Use Cases
case is useful whenever one input can lead to several known outcomes.
Common practical examples
Menu selection in command-line apps
choice = "delete"
case choice
when "list"
puts "Showing records"
when "create"
puts "Creating record"
when "delete"
puts "Deleting record"
else
puts "Invalid command"
end
API status handling
status = 404
case status
when 200
puts "Success"
when 404
puts "Not found"
when 500
puts "Server error"
else
puts "Unexpected status"
end
Role-based messaging
role = "editor"
case role
puts
puts
puts
puts
Real Codebase Usage
In real Ruby projects, developers often use case for clean branching when there is one main value being examined.
Common patterns
1. Mapping values to outputs
def badge_color(status)
case status
when "success"
"green"
when "warning"
"yellow"
when "error"
"red"
else
"gray"
end
end
This is common in helpers, presenters, and formatting code.
2. Validation and normalization
def normalize_role(role)
case role
when "admin", "owner"
"admin"
when "writer", "editor"
"editor"
else
"guest"
end
end
Common Mistakes
1. Trying to use switch
Ruby does not have a switch keyword.
Incorrect
switch role
when "admin"
puts "Full access"
end
Correct
case role
when "admin"
puts "Full access"
end
2. Forgetting end
Ruby blocks must be closed with end.
Broken code
case color
when "red"
puts "Stop"
This will raise a syntax error.
Correct
case color
when "red"
puts "Stop"
end
Comparisons
| Concept | Best for | Example shape | Notes |
|---|---|---|---|
case | Comparing one value against many options | case role | Ruby's switch-style structure |
if / elsif / else | General conditional logic | if age > 18 | Better for complex boolean expressions |
unless | A single negative condition | unless logged_in | Best for simple negative checks |
case vs if/elsif
Use case when all branches depend on the same value:
Cheat Sheet
Quick syntax
case value
when option1
# code
when option2
# code
else
# fallback
end
Key points
- Ruby uses
case, notswitch - Use
whenfor each possible match - Use
elsefor the fallback branch - Ruby stops at the first matching
when casecan return a value- Multiple matches can go in one
when
Multiple values in one branch
case letter
when "a", "e", "i", "o", "u"
puts "Vowel"
end
Assign from a case
FAQ
Is there a switch statement in Ruby?
Ruby does not have a switch keyword. The equivalent feature is case.
How do you write switch logic in Ruby?
Use a case expression with one or more when branches and an optional else.
case value
when 1
puts "One"
else
puts "Other"
end
What is the difference between case and if in Ruby?
case is best when comparing one value against several options. if is better for general true/false conditions.
Does Ruby case need break?
No. Ruby does not normally fall through to the next branch, so break is not needed.
Can Ruby case return a value?
Mini Project
Description
Build a small command-line status labeler for an order system. The program will take an order status and print a user-friendly message. This demonstrates how case makes multi-branch decision logic easier to read than a long chain of if statements.
Goal
Create a Ruby program that converts order status values into clear messages using a case expression.
Requirements
- Create a variable named
statuswith a string value - Use a
caseexpression to handle at least four statuses - Print a different message for each known status
- Include an
elsebranch for unknown statuses
Keep learning
Related questions
How to Call Shell Commands from Ruby and Capture Output
Learn how to run shell commands in Ruby, capture output, check exit status, and choose the right method for scripts and apps.
How to Check Whether a String Contains a Substring in Ruby
Learn how to check if a string contains a substring in Ruby using include?, match, and multiline string examples.
How to Check if a Hash Key Exists in Ruby
Learn how to check whether a specific key exists in a Ruby hash using key?, has_key?, and include? with clear examples.