arrow_backward Back to blog

Ruby Quick Tip: Regular Expressions in Case Statements

Did you know that you can use regular expressions in case statements in Ruby to check for a match? For instance, if I’m implementing some method_missing functionality and I want to check for bang or question methods, I might be tempted to do something like this:

But it’d be much cleaner if instead it looked like this:

This is great, but now what if we want to call out a method for bang and question methods? Thankfully Ruby has us covered there as well:

By using the $1 global variable we can access the last regular expression match performed by ruby. This is just one of those little details that makes working with Ruby such a joy.

arrow_backBack

New Project Request