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.
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
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.
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!
Case statements in Ruby are versatile and can be used in various ways:
case fruit
when 'apple', 'pear'
puts "It's a pome fruit"
when 'orange', 'lemon'
puts "It's a citrus fruit"
end
case age
when 0..12
puts "Child"
when 13..19
puts "Teenager"
when 20..65
puts "Adult"
else
puts "Senior"
end
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
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.