95

I know that I can write a Ruby case statement to check a match against a regular expressions. However, I'd like to use the match data in my return statement. Something like this semi-pseudocode:

foo = "10/10/2011"

case foo
    when /^([0-9][0-9])/
        print "the month is #{match[1]}"
    else
        print "something else"
end

How can I achieve that?

Thanks!


Just a note: I understand that I wouldn't ever use a switch statement for a simple case as above, but that is only one example. In reality, what I am trying to achieve is the matching of many potential regular expressions for a date that can be written in various ways, and then parsing it with Ruby's Date class accordingly.

2
  • 1
    Ruby's Date.parse understands many date formats. Have you tried it?
    – raine
    Jul 24, 2011 at 9:32
  • Although it doesn't answer this question, you might want to look at the Chronic gem...
    – DGM
    Dec 8, 2011 at 5:05

2 Answers 2

169

The references to the latest regex matching groups are always stored in pseudo variables $1 to $9:

case foo
when /^([0-9][0-9])/
    print "the month is #{$1}"
else
    print "something else"
end

You can also use the $LAST_MATCH_INFO pseudo variable to get at the whole MatchData object. This can be useful when using named captures:

case foo
when /^(?<number>[0-9][0-9])/
    print "the month is #{$LAST_MATCH_INFO['number']}"
else
    print "something else"
end
5
  • 1
    @Yossi Do you have a source for your comment regarding thread safety? I just did an experiment in ruby 1.8.7 that seems to indicate that it is thread-safe! (Thread matching a regex every one second - checking in irb if local matches are getting clobbered)
    – Joel
    Nov 28, 2011 at 4:44
  • 6
    -1 $variables to do with regular expressions are not global even though it has a dollar sign in front of it. Dec 8, 2011 at 3:49
  • @AndrewGrimm Thanks for pointing this out. I wasn't aware of it. I'll have to change a lot of old code :-/
    – Yossi
    Dec 21, 2011 at 20:46
  • 2
    You can also do $1, $2 ... $9 or Regexp.last_match(1) as recommended by rubocop Jan 10, 2019 at 23:23
  • If $LAST_MATCH_INFO isn't available you'll either need to use $~, or require 'English' which sets up the alias
    – aidan
    Nov 25, 2022 at 3:02
6

Here's an alternative approach that gets you the same result but doesn't use a switch. If you put your regular expressions in an array, you could do something like this:

res = [ /pat1/, /pat2/, ... ]
m   = nil
res.find { |re| m = foo.match(re) }
# Do what you will with `m` now.

Declaring m outside the block allows it to still be available after find is done with the block and find will stop as soon as the block returns a true value so you get the same shortcutting behavior that a switch gives you. This gives you the full MatchData if you need it (perhaps you want to use named capture groups in your regexes) and nicely separates your regexes from your search logic (which may or may not yield clearer code), you could even load your regexes from a config file or choose which set of them you wanted at run time.

1
  • I was also thinking about thread safety using the case approach. Maybe you want to use mu's approach in a threaded scenario, rather than a global variable with the case approach(?)
    – Casper
    Jul 24, 2011 at 0:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.