Ruby Case
The case
statement in Ruby is a powerful control flow mechanism that allows you to test a value against multiple conditions and execute different portions of code based on the result. In this article, we'll explore how to use the case
statement in Ruby.
Syntax
The syntax of the Ruby case
statement is as follows:
case expression
when condition1
# code to execute when the condition1 is true
when condition2
# code to execute when the condition2 is true
when condition3
# code to execute when the condition3 is true
else
# code to execute when none of the conditions are true
end
Example
Here's a simple example that uses the case
statement to determine the day of the week:
day = Time.new.wday
case day
when 0
puts "Today is Sunday"
when 1
puts "Today is Monday"
when 2
puts "Today is Tuesday"
when 3
puts "Today is Wednesday"
when 4
puts "Today is Thursday"
when 5
puts "Today is Friday"
when 6
puts "Today is Saturday"
else
puts "Invalid day"
end
Output
Today is Monday
Explanation
In the above example, we have assigned the value of Time.new.wday
to the variable day
. The wday
method returns the day of the week as an integer, with 0 representing Sunday and 6 representing Saturday.
The case
statement then checks the value of the day
variable against each of the conditions specified using the when
keyword. When a match is found, the code block following the condition is executed. If none of the conditions match, the else
block is executed.
Use
The case
statement is useful in situations where you need to test a value against multiple conditions and execute different portions of code based on the result. It can be used instead of a series of if
statements, resulting in cleaner and more concise code.
Important Points
- The
case
statement allows you to test a value against multiple conditions and execute different portions of code based on the result. - The
case
statement is an alternative to a series ofif
statements. - The
else
block is executed when none of the conditions match. - The
case
statement can improve the readability and maintainability of your code.
Summary
The case
statement is a powerful control flow mechanism in Ruby that allows you to test a value against multiple conditions and execute different portions of code based on the result. It's an alternative to a series of if
statements and can improve the readability and maintainability of your code.