In Ruby, a case statement is used as a switch statement to compare a value against multiple conditions. Here’s the syntax and an example:
Syntax:
case variable
when value1
# Code to execute if variable == value1
when value2
# Code to execute if variable == value2
else
# Code to execute if no matches
end
Example:
day = “Monday”
case day
when “Monday”
puts “Start of the workweek!”
when “Friday”
puts “Almost the weekend!”
else
puts “Just another day.”
end
Output:
Start of the workweek!
Key Points:
Use case to specify the variable being compared.
Use when for each condition.
Use else for a default case if no conditions match.