Using case with ranges and patterns helps you check where a value fits in a group or matches a shape. It makes your code cleaner and easier to read.
0
0
Case with ranges and patterns in Ruby
Introduction
You want to check if a number falls within certain ranges, like grades or ages.
You need to match a value against different patterns, like arrays or hashes with specific keys.
You want to replace many <code>if-elsif</code> statements with a simpler structure.
You want your code to clearly show different cases for different value groups.
Syntax
Ruby
case variable in pattern1 # code for pattern1 in pattern2 # code for pattern2 else # code if no pattern matches end
Use in to match patterns or ranges inside a case statement.
Ranges use start..end and match if the variable is inside that range.
Examples
This example checks which range the score fits in and prints the result.
Ruby
case score in 0..59 puts "Fail" in 60..79 puts "Pass" in 80..100 puts "Excellent" else puts "Invalid score" end
This example matches
data if it is an array with two elements or a hash with keys name and age.Ruby
case data in [x, y] puts "Array with two elements: #{x} and #{y}" in {name: name, age: age} puts "Hash with name #{name} and age #{age}" else puts "Unknown format" end
Sample Program
This program defines a method that uses case with ranges and patterns to describe the input value. It shows how different inputs match different cases.
Ruby
def describe_value(value) case value in 1..10 "Value is between 1 and 10" in 11..20 "Value is between 11 and 20" in [a, b] "Value is an array with two elements: #{a} and #{b}" in {name: name, age: age} "Value is a hash with name #{name} and age #{age}" else "Value does not match any pattern" end end puts describe_value(7) puts describe_value(15) puts describe_value([3, 4]) puts describe_value({name: "Alice", age: 30}) puts describe_value("hello")
OutputSuccess
Important Notes
Patterns can match arrays, hashes, and ranges to check the shape or value group.
If no pattern matches, the else block runs.
Pattern matching with case was added in Ruby 2.7 and improved in Ruby 3.x.
Summary
Case with ranges and patterns lets you check if a value fits in a range or matches a shape.
Use in inside case to match ranges like 1..10 or patterns like arrays and hashes.
This makes your code easier to read and reduces many if-elsif checks.