Thuta Learning
IntermediateProgrammingbeginner

Case Statements

Relax. We'll talk through this in plain words — no textbook voice.

case statements keep your code cleaner when you're comparing one value against many possible options. They're great for handling things like grades, menu choices, user roles, or status codes.

ruby
grade = "B"

case grade
when "A"
  puts "Excellent!"
when "B"
  puts "Good job!"
when "C"
  puts "Keep practicing."
else
  puts "Invalid grade."
end

case grade takes the grade value and checks it against each when in turn. If nothing matches, else runs instead.

You should see
Good job!

Info

When you have too many options, case is easier to read than a long chain of if elsif statements.

Easy traps

  • If you don't include an else, values that don't match anything will simply be skipped with no action taken. Add an else if you need default behavior.
Case Statements | Thuta Learning