Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
150: Pattern Matching with case/in (Ruby 3)
If you've been using Ruby for a while, you've probably written a hundred case/when statements. Because of that, you might look at the newer case/in syntax and think, "Why do I need this? It looks like the same thing with a different keyword."
"It's just a fancier version of case/when"
Here is the misconception: thinking that in is just a synonym for when. In a traditional case/when block, Ruby uses the === operator to see if the subject matches a value. It's a check for equality or type. It tells you if something is true, but it doesn't help you get data out of the object.
# The old way: checking for equality
response = { status: 200, body: { user_id: 42, name: "Alice" } }
case response
when { status: 200 }
# I know it's a success, but I still have to manually
# dig into the hash to get the user_id.
puts "Success! User is #{response[:body][:user_id]}"
end
In the example above, the when clause checks if the hash contains the key status: 200. It's a boolean check. If it passes, you still have to do the tedious work of manually accessing the nested keys. It's clunky, and if the structure changes slightly, your code crashes with a NoMethodError on nil.
Pattern matching is about shape, not just equality
Now, let's look at case/in. The fundamental difference is that pattern matching doesn't just ask "Is this equal to X?" It asks "Does this object have the shape I expect, and if so, can you give me the pieces inside?"
# The Ruby 3 way: destructuring and binding
response = { status: 200, body: { user_id: 42, name: "Alice" } }
case response
in { status: 200, body: { user_id: id, name: name } }
# Ruby doesn't just match the shape; it extracts the values
# and assigns them to local variables 'id' and 'name' automatically.
puts "Success! User #{name} has ID #{id}"
in { status: 404 }
puts "User not found."
else
puts "Something went wrong."
end
See what happened there? I didn't have to write id = response[:body][:user_id]. By placing id and name inside the pattern, I told Ruby: "If the hash matches this specific nested structure, grab the value at this position and bind it to this variable name." This is called destructuring. I love it because it makes the "happy path" of your data processing incredibly explicit.
Binding variables versus pinning values
This leads to a tricky spot where a lot of learners get stuck. You might wonder: "If I put a word like id in the pattern, how does Ruby know I want to create a variable instead of checking if the value is actually the string 'id'?"
In a pattern, any symbol or variable name that hasn't been defined yet is treated as a capture. Ruby assumes you want to bind the value to that name. But what if you actually want to match a specific value? That's where the "pin" operator (^) comes in.
admin_id = 1
user_data = { id: 1, role: "admin" }
case user_data
in { id: ^admin_id, role: "admin" }
puts "The admin is logged in!"
in { id: id, role: role }
puts "User #{id} is a #{role}"
end
Without that ^, Ruby would have simply taken whatever id was in the hash and reassigned the local variable admin_id to that value. By "pinning" it, you're telling Ruby: "Don't bind a new variable here; use the existing value of admin_id for a strict equality check."
Handling arrays and versatility
This isn't limited to hashes. It's arguably even more powerful with arrays. You can match the start of an array, the end, or even a variable number of elements using the * (splat) operator.
command = ["move", "north", "fast", "stealthily"]
case command
in ["move", direction, *modifiers]
puts "Moving #{direction} with these modifiers: #{modifiers.join(', ')}"
in ["quit"]
puts "Goodbye!"
end
In one line, I've validated that the command starts with "move", extracted the direction, and gathered every other subsequent element into a modifiers array. Doing this with if/else and array indexing is a nightmare to read and maintain.
📋 Practical Task
Build a Webhook Event Dispatcher
You are building a system that receives JSON-like hashes from a third-party payment provider. The payloads vary significantly based on the event type. Your goal is to create a dispatcher that uses case/in to extract specific data from these payloads.
Requirements:
- Implement a method
process_event(payload). - If the payload is
{ type: "payment_success", data: { amount: X, currency: Y } }, it should return a string:"Processed payment of X Y". - If the payload is
{ type: "customer_updated", data: { id: Z, changes: [...] } }, it should return a string:"Customer Z updated". - If the payload is
{ type: "system_alert", priority: "high", message: M }, it should return a string:"URGENT: M". - For any other shape, return
"Unknown event".
Starter Code:
def process_event(payload)
# Your case/in logic here
end
# Test cases
puts process_event({ type: "payment_success", data: { amount: 100, currency: "USD" } })
# Expected: "Processed payment of 100 USD"
puts process_event({ type: "customer_updated", data: { id: 456, changes: ["email"] } })
# Expected: "Customer 456 updated"
puts process_event({ type: "system_alert", priority: "high", message: "Server Down" })
# Expected: "URGENT: Server Down"
puts process_event({ type: "ping" })
# Expected: "Unknown event"There are no comments for now.