Skip to Content
Course content

150: Pattern Matching with case/in (Ruby 3)

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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"
Rating
0 0

There are no comments for now.

to be the first to leave a comment.