Basics

Ruby Case

Case Expressions

Ruby case expressions handle conditions with when clauses.

Introduction to Ruby Case Statements

The case statement in Ruby is a powerful tool for handling multiple conditions. It's often compared to switch statements found in other programming languages. With case, you can evaluate a single variable against different possible values using when clauses, making your code cleaner and more readable.

Basic Syntax of Case Statements

A Ruby case statement begins with the keyword case, followed by an expression whose value you want to compare. Each when clause checks the expression against a specific value. An optional else clause can be added to handle any cases not covered by a when clause.

Example: Using Case in Ruby

Below is a simple example demonstrating how to use a case statement in Ruby to determine a person's grade based on their score:

In this example, the case statement evaluates the score variable to determine which range it falls into, and prints the corresponding message.

Using Multiple Conditions in When Clauses

Ruby allows you to check multiple conditions in a single when clause by separating each condition with a comma. This feature can simplify your code when you want to perform the same action for multiple conditions.

In this example, the case statement evaluates the weather variable. If it's either "rainy" or "stormy", it prints a message to take an umbrella. If it's "sunny" or "cloudy", it suggests wearing sunglasses.

Using Case Without an Expression

Ruby also allows you to use a case statement without an expression. This approach is useful for testing multiple conditions independently.

Here, the case statement is used without a specific expression. Each when clause checks a different condition related to the age variable, outputting the appropriate message based on the age range.

Conclusion

Ruby's case statement is a versatile way to handle multiple conditions in your code. By using when clauses, you can make your code cleaner and more intuitive. Whether you're comparing a single expression to multiple values, checking multiple conditions at once, or using ranges, the case statement provides a clear and efficient solution.

Previous
If Else
Next
Loops