How to write a switch statement in Ruby?

 

In Ruby, there is no built-in switch statement like in some other programming languages. Instead, you can achieve similar functionality using a case statement. Here's how you can write a case statement in Ruby, along with an example:

ruby
def get_day_name(day_number) case day_number when 1 return "Monday" when 2 return "Tuesday" when 3 return "Wednesday" when 4 return "Thursday" when 5 return "Friday" when 6 return "Saturday" when 7 return "Sunday" else return "Invalid day number" end end day_number = 3 day_name = get_day_name(day_number) puts "Day #{day_number} is #{day_name}"

In this example, the case statement takes an expression (day_number in this case) and compares it against different when conditions. If the expression matches any of the when conditions, the corresponding code block is executed. If none of the conditions match, the code block under else is executed.

Keep in mind that in Ruby, you can use any objects as the targets of the case expression, not just integers. The comparison is done using the === operator, which allows for more flexible matching.

Comments