0
0
Rubyprogramming~3 mins

Why Case with ranges and patterns in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could replace messy if-else chains with neat, readable patterns that just work?

The Scenario

Imagine you have to check a number and decide what category it belongs to, like age groups or score levels, by writing many if-else statements for each range.

The Problem

This manual way is slow to write, hard to read, and easy to make mistakes, especially when ranges overlap or you miss a case.

The Solution

Using case with ranges and patterns lets you write clear, neat checks that automatically match numbers in ranges or patterns, making your code simpler and less error-prone.

Before vs After
Before
if score >= 0 && score <= 50
  puts 'Low'
elsif score > 50 && score <= 80
  puts 'Medium'
else
  puts 'High'
end
After
case score
in 0..50 then puts 'Low'
in 51..80 then puts 'Medium'
else puts 'High'
end
What It Enables

This lets you write clean, readable code that easily handles complex conditions with ranges and patterns.

Real Life Example

For example, categorizing students by their test scores into grades like A, B, C using simple range patterns instead of many if-else checks.

Key Takeaways

Manual checks with many if-else are slow and error-prone.

Case with ranges and patterns makes code cleaner and easier to read.

It helps handle complex conditions simply and safely.