Back to Blog

Get in Touch

Ruby Quick Tip: Regular Expressions in Case Statements

By Michael Bleigh March 29, 2010 in ruby, quick tip, regular expressions, case

Missing

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:

def method_missing(name, *args)
  name = name.to_s
  if name.match(/!$/)
    puts "Bang Method!"
  elsif name.match(/\?$/)
    puts "Query Method?"
  else
    super
  end
end

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

def method_missing(name, *args)
  case name.to_s
    when /!$/
      puts "Bang Method!"
    when /\?$/
      puts "Query Method?"
    else
      super
  end
end

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:

def method_missing(name, *args)
  case name.to_s
    when /^(.*)!$/
      bang_method($1)
    when /^(.*)\?$/
      question_method($1)
    else
      super
  end
end

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.

Medium

Michael Bleigh

Michael has been with Intridea since 2007 and works to build Intridea's portfolio of products. With many years of experience working as both a designer and a developer, Michael specializes in helping to bridge the gap between the back-end development and the front-end design of a project. Michael is a prolific member of the Ruby on Rails community, having released popular open source libraries such as OmniAuth and spoken at conferences including RailsConf and RubyConf.

More from our blog

RSpec the Unexpected

Read Now →
X

More posts by Michael Bleigh

Michael Bleigh

To the troubling idea isn't about what signal you're sending to your employee...

Michael Bleigh

Node.js has a pattern that I personally enjoy: if you require a directory, it...

Michael Bleigh

Last weekend I had the opportunity to speak at RubyConf 2012 about a topic th...