0
0
Rubyprogramming~5 mins

Case/when statement in Ruby

Choose your learning style9 modes available
Introduction

The case/when statement helps you choose what to do based on different conditions. It makes your code cleaner and easier to read when you have many choices.

When you want to perform different actions depending on a value, like days of the week.
When you have multiple options and want to avoid many if/else statements.
When you want to check a variable against several possible values.
When you want to make your code easier to understand by grouping conditions clearly.
Syntax
Ruby
case variable
when value1
  # code to run if variable === value1
when value2
  # code to run if variable === value2
else
  # code to run if no match
end
The case keyword starts the statement, and when checks each possible value.
The else part is optional and runs if no when matches.
Examples
This checks the value of day and prints a message based on it.
Ruby
case day
when "Monday"
  puts "Start of the week"
when "Friday"
  puts "Almost weekend"
else
  puts "Just another day"
end
You can check multiple values or ranges in one when line.
Ruby
case number
when 1, 2, 3
  puts "Small number"
when 4..6
  puts "Medium number"
else
  puts "Other number"
end
Sample Program

This program asks the user to enter a fruit name and then tells them which fruit they chose using a case/when statement.

Ruby
puts "Enter a fruit name:"
fruit = gets.chomp
case fruit.downcase
when "apple"
  puts "You chose apple."
when "banana"
  puts "You chose banana."
when "orange"
  puts "You chose orange."
else
  puts "Unknown fruit."
end
OutputSuccess
Important Notes

The case statement compares using === operator, so it works well with ranges and classes.

Remember to use end to close the case statement.

Summary

The case/when statement helps you pick actions based on a value.

It is cleaner than many if/else statements when checking many options.

You can check multiple values or ranges in one when line.