Start Coding

Topics

Ruby Case Statements

Case statements in Ruby provide a concise way to compare a value against multiple conditions. They offer an alternative to lengthy if-else chains, making code more readable and maintainable.

Basic Syntax

The basic structure of a Ruby case statement is as follows:


case expression
when value1
    # code to execute if expression == value1
when value2
    # code to execute if expression == value2
else
    # code to execute if no match is found
end
    

How It Works

Ruby evaluates the expression and compares it to each when clause using the === operator. This allows for flexible matching, including class checking and regular expressions.

Example: Simple Comparison


grade = 'B'

case grade
when 'A'
    puts "Excellent!"
when 'B'
    puts "Good job!"
when 'C'
    puts "Acceptable"
else
    puts "Need improvement"
end

# Output: Good job!
    

Advanced Usage

Case statements in Ruby are versatile and can be used in various ways:

1. Multiple Values per When Clause


case fruit
when 'apple', 'pear'
    puts "It's a pome fruit"
when 'orange', 'lemon'
    puts "It's a citrus fruit"
end
    

2. Range Matching


case age
when 0..12
    puts "Child"
when 13..19
    puts "Teenager"
when 20..65
    puts "Adult"
else
    puts "Senior"
end
    

3. Class Matching

Case statements can check object types:


case data
when String
    puts "It's a string"
when Integer
    puts "It's an integer"
when Array
    puts "It's an array"
else
    puts "Unknown type"
end
    

Best Practices

  • Use case statements when you have multiple conditions to check against a single value.
  • Prefer case over long if-else chains for better readability.
  • Utilize the power of === for flexible matching, including regular expressions and ranges.
  • Consider using Ruby If-Else Statements for simpler conditions.

Related Concepts

To further enhance your Ruby skills, explore these related topics:

Understanding case statements is crucial for writing clean and efficient Ruby code. They offer a powerful tool for handling multiple conditions elegantly.