Question

How to Write a Switch Statement in Ruby

rubyswitch-statementconditional-statements

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.

day = "monday"

case day
when "monday"
  puts "Start of the work week"
when "friday"
  puts "Almost the weekend"
else
  puts "Just another day"
end

case is an expression

In Ruby, case can return a value.

role = "admin"

message = case role
when "admin"
  "Full access"
when "editor"
  "Can edit content"
else
  "Limited access"
end

puts message

This is very common in Ruby code because it keeps assignments concise and readable.

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.

Take Quiz

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 score with each when value
  • Since score is 2, it runs puts "Intermediate"
  • The rest of the branches are skipped

Example: multiple values in one when

letter = "a"

case letter
when "a", "e", "i", "o", "u"
  puts "Vowel"
else
  puts "Not a vowel"
end

This is useful when several values should produce the same result.

Example: returning a value

status = "paid"

label = case status
when "pending"
  "Waiting for payment"
when "paid"
  "Order confirmed"
when "shipped"
  "On the way"
else
  "Unknown status"
end

puts label

Here, the case expression returns a string, which is stored in label.

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

  1. Ruby sets fruit to "apple".
  2. Ruby starts the case fruit expression.
  3. It checks the first branch: when "banana".
  4. "apple" does not match "banana", so Ruby moves on.
  5. It checks the next branch: when "apple".
  6. This matches.
  7. Ruby runs:
puts "Red or green"
  1. Ruby stops checking further branches.
  2. The else branch is ignored because a match was already found.

Output

Red or green

Key rule

Ruby executes only the first matching when branch.

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
when "admin"
  puts "Can manage everything"
when "editor"
  puts "Can update content"
when "viewer"
  puts "Read-only access"
else
  puts "Unknown role"
end

Categorizing values

You may also see case used to group inputs into categories such as age groups, file types, or score levels.

Take Quiz

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

This helps convert many possible inputs into one standard result.

3. Guarding unknown values

def shipping_message(method)
  case method
  when "pickup"
    "Collect from store"
  when "delivery"
    "Shipped to address"
  else
    raise ArgumentError, "Unknown shipping method: #{method}"
  end
end

This pattern is useful when an unexpected value should fail fast.

4. Replacing long elsif chains

If every branch checks the same variable, developers often refactor from this:

if role == "admin"
  "full"
elsif role == "editor"
  "limited"
else
  "none"
end

To this:

case role
when "admin"
  "full"
when "editor"
  "limited"
else
  "none"
end

The second version is usually easier to scan.

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

3. Using = instead of matching by case

Beginners sometimes try to assign inside conditions.

Broken idea

if role = "admin"
  puts "Full access"
end

This assigns a value instead of comparing properly.

If you are choosing between many values of one variable, use case.

case role
when "admin"
  puts "Full access"
end

4. Expecting every matching branch to run

Ruby stops at the first matching when.

value = 1

case value
when 1
  puts "First"
when 1
  puts "Second"
end

Only First will print.

5. Forgetting else

If no branch matches and there is no else, nothing happens.

command = "update"

case command
when "create"
  puts "Creating"
when "delete"
  puts "Deleting"
end

This may be fine sometimes, but often it is safer to handle unknown values explicitly.

else
  puts "Unknown command"

6. Using case when if is clearer

If your branches use different conditions instead of one shared value, if may be a better choice.

age = 20

if age >= 18
  puts "Adult"
else
  puts "Minor"
end

This is often clearer than forcing the logic into case.

Comparisons

ConceptBest forExample shapeNotes
caseComparing one value against many optionscase roleRuby's switch-style structure
if / elsif / elseGeneral conditional logicif age > 18Better for complex boolean expressions
unlessA single negative conditionunless logged_inBest for simple negative checks

case vs if/elsif

Use case when all branches depend on the same value:

case status
when "open"
  puts "Open"
when "closed"
  puts "Closed"
end

Use if/elsif when each branch has a different condition:

if score >= 90
  puts "A"
elsif score >= 80
  puts "B"
else
  puts "C"
end

Ruby case vs switch in other languages

FeatureRuby caseTraditional switch
Keywordcaseoften switch
Branch keywordwhenoften case
Default branchelseoften default
Falls through automaticallyNoOften yes in some languages
Returns a valueYesDepends on language

A useful Ruby advantage is that case does not normally fall through from one branch to the next, which helps avoid a common source of bugs in other languages.

Take Quiz

Cheat Sheet

Quick syntax

case value
when option1
  # code
when option2
  # code
else
  # fallback
end

Key points

  • Ruby uses case, not switch
  • Use when for each possible match
  • Use else for the fallback branch
  • Ruby stops at the first matching when
  • case can 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

message = case status
when "ok"
  "Success"
else
  "Unknown"
end

Choose case when

  • one variable is being checked
  • there are several known possible values
  • readability matters

Choose if/elsif when

  • conditions are different expressions
  • you are checking ranges or boolean logic directly in a clearer way

Common fallback pattern

else
  raise ArgumentError, "Unexpected value"

Remember

  • no switch keyword in Ruby
  • do not forget end
  • else is optional but often useful

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?

Yes. This is very common.

result = case role
when "admin"
  "full"
else
  "limited"
end

Can one when match multiple values?

Yes.

when "yes", "y", true

Is else required in Ruby case?

No, but it is often helpful to handle unexpected values.

Take Quiz

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 status with a string value
  • Use a case expression to handle at least four statuses
  • Print a different message for each known status
  • Include an else branch for unknown statuses
Take Quiz

Keep learning

Related questions

View more