Ruby Case Statement

Learn via video courses
Topics Covered

Overview

The case statement in Ruby, also known as the switch statement in other programming languages, provides a convenient way to perform different actions based on the value of a variable or expression. It allows you to evaluate multiple conditions and execute the corresponding code block for the first condition that matches. The case statement enhances the readability and maintainability of your code by reducing the need for multiple if-else statements.

In this article, we will explore the syntax, parameters, return value, exceptions, and various features of the Ruby case statement, along with examples and MCQs to solidify your understanding.

Case Statement in Ruby

The case statement is a powerful control structure in Ruby that helps you handle multiple conditions efficiently. It evaluates an expression and compares it against several possible values using the when keyword.

Once a match is found, the corresponding code block is executed. If none of the conditions match, the code block under the else clause (optional) is executed. The case statement allows you to structure your code logically and easily handle different scenarios.

Syntax

The syntax of the case statement in Ruby is as follows:

Explanation:

  • The case keyword is used to initiate the case statement block.
  • It is followed by the expression, which can be a variable or an expression that you want to evaluate.
  • The when keyword is used to specify the conditions to compare against the expression.
  • You can have multiple when clauses to handle different cases.
  • The else keyword is optional and is used to define the code block that executes when none of the conditions in the when clauses match the expression.
  • Finally, the end keyword marks the end of the case statement.

Parameters

The case statement takes an expression as its parameter, which is the value or variable you want to evaluate. This expression can be of any data type supported in Ruby, including strings, numbers, booleans, or even objects. The case statement will compare the expression against the values specified in the when clauses to determine which code block to execute.

Return Value

The return value of the case statement depends on the code executed within the matching when clause. If the code block contains a return statement, the value returned will be the value of that statement. If no return statement is present, the value of the last evaluated expression within the code block will be returned. If none of the conditions match and there is no else clause, the return value of the case statement will be nil.

Exception

The case statement does not raise any exceptions on its own. However, if you have code within the case statement's code blocks that may raise exceptions, those exceptions will be raised and can be handled using appropriate error-handling techniques such as begin and rescue blocks.

Examples

Let's go through a few examples to illustrate the usage of the case statement in Ruby:

Example 1: Which Fruit is It?

Output:

In this example, the fruit variable is evaluated, and the code block under the matching when clause is executed. Since fruit is set to "apple", the first condition matches, and "It's an apple!" is printed.

Example 2: Grading System

Output:

In this example, the grade variable is compared against different ranges to determine the corresponding letter grade. Since grade is 8585, it falls within the range of 8080 to 8989, and "B" is printed.

Example 3: Days of Week

Output:

The code block under the first when clause is executed in this example because the day variable is set to "Monday". It prints "It's a weekday" to the console.

Example 4: Data Type Matching

Output:

In this example, the code block under the third when clause is executed because the value variable is a float. It prints "It's a float" to the console.

Example 5: Array Matching

Output:

In this example, the code block under the second when clause is executed because the array variable matches the specified array. It prints "It's a five-element array" to the console.

Example 6: Child or Senior

The case statement in Ruby also supports ranges as values for comparison. Ranges allow you to define a set of values and check if the expression falls within that range. For example:

In this example, the age variable is compared against different ranges to determine the age group. If the age is between 00 and 1212 (inclusive), the code block under the first when clause is executed, and so on. Ranges provide a concise and expressive way to handle conditions within the case statement.

Regular Expressions in the Case Statement

The case statement in Ruby can also use regular expressions as values for comparison. Regular expressions are powerful tools for pattern matching, allowing you to handle complex conditions efficiently. For example:

In this example, the email variable is matched against a regular expression that checks for the validity of an email address. If the email matches the regular expression, the code block under the when clause is executed, indicating a valid email address; otherwise, the code block under the else clause is executed.

Lambdas in the Case Statement

The case statement in Ruby also allows you to use lambdas as conditions. Lambdas are anonymous functions that can be assigned to variables and used as first-class objects. You can define a lambda and use it as a condition in the when clause. For example:

In this example, a lambda named even is defined to check if a number is even. The number variable is then evaluated against the even lambda within the when clause. If the condition is satisfied, the code block under the when clause is executed, indicating an even number. Otherwise, the code block under the else clause is executed.

Using then Keyword

In addition to the when keyword, the Ruby case statement also supports the optional use of the then keyword. The then keyword can be placed after the condition in a when clause and serves as a visual indicator for the code block that should be executed if the condition matches.

Here's an example that demonstrates the usage of the then keyword:

In this example, the code block to be executed is specified after the then keyword. This syntax enhances the readability of the code by explicitly separating the condition and the associated code block. However, it's important to note that using then is optional, and you can omit it if you prefer a more concise syntax.

Flow Chart

To better understand the flow of execution in a case statement, let's take a look at a simplified flow chart:

Nested Case Statements

In Ruby, you can have a case statement within another case statement, allowing for more complex branching and logic. This is known as nested case statements. With nested case statements, you can handle multiple levels of conditions and make your code more structured and readable.

Consider the following example:

Output:

In this example, the outer case statement checks the role, and if it matches "admin", it goes into the nested case statement to check the permission. This allows for granular control and handling of different combinations of conditions.

Conclusion

  • The case statement in Ruby provides a concise and readable way to handle multiple conditions.
  • It allows you to evaluate an expression and perform different actions based on the matching condition.
  • The syntax of the case statement in Ruby is as follows:
  • The case statement takes an expression as its parameter, which is the value or variable you want to evaluate. This expression can be of any data type supported in Ruby, including strings, numbers, booleans, or even objects.
  • The return value of the case statement depends on the code executed within the matching when clause.
  • The then keyword can be placed after the condition in a when clause and serves as a visual indicator for the code block that should be executed if the condition matches.
  • Ruby also allows the usage of nested case statements which stand for case statement inside an another case statement. With nested case statements, you can handle multiple levels of conditions and make your code more structured and readable.