Ruby - Case Statement

1. Introduction

In Ruby, the case statement provides an alternative to multiple if-elsif conditions, enabling developers to create more readable and concise code for multiple checks against a single value. This guide will explore how to implement and use the case statement in Ruby.

2. Program Steps

1. Define a variable with a value.

2. Use a case statement to match the variable's value against several conditions.

3. For each condition, specify a code block to execute.

4. Optionally, define an else within the case statement as a fallback if none of the conditions are met.

5. Print out relevant messages based on the matched condition.

3. Code Program

# Defining a variable with a value
fruit = "apple"
# Using case statement to match the fruit's value
case fruit
when "apple"
  puts "It's an apple!"
when "banana"
  puts "It's a banana!"
when "cherry"
  puts "It's a cherry!"
else
  puts "It's not a fruit we recognize."
end

Output:

It's an apple!

Explanation:

1. The variable fruit is assigned the value "apple".

2. The case statement checks the value of fruit against its when conditions.

3. The value "apple" matches the first when condition: when "apple".

4. The corresponding code block is executed, printing the message "It's an apple!".

5. If the fruit variable held a value not listed in any of the when conditions, the code within the else block would execute, printing "It's not a fruit we recognize."

The case statement simplifies the process of checking a single variable against multiple potential values, offering a cleaner and more readable approach compared to several if-elsif statements.


Comments