Monday, January 13, 2025
HomeQ&AHow to write a switch statement in Ruby

How to write a switch statement in Ruby

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

See also  What are some recommended dating sites/apps for finding.....

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.

See also  How much water do I use for 2 cups of rice?

Use when for each condition.

Use else for a default case if no conditions match.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x