evianpring evianpring - 10 months ago 32
Ruby Question

What is the difference between these three alternative ways to write Ruby regular expressions?

I want to match the path "/". I've tried the following alternatives, and the first two do match, but I don't know why the third doesn't:

/\A\/\z/.match("/") # <MatchData "/">
"/\A\/\z/".match("/") # <MatchData "/">
Regexp.new("/\A\/\z/").match("/") # nil

What's going on here? Why are they different?


The first snippet is the only correct one.

The second example is... misleading. That string literal "/\A\/\z/" is, obviously, not a regex. It's a string. Strings have #match method which converts its argument to a regexp (if not already one) and match against it. So, in this example, it's '/' that is the regular expression, and it matches a forward slash found in the other string.

The third line is completely broken: don't need the surrounding slashes there, they are part of regex literal, which you didn't use. Also use single quoted strings, not double quoted (which try to interpret escape sequences like \A)

Regexp.new('\A\/\z').match("/") # => #<MatchData "/">

And, of course, none of the above is needed if you just want to check if a string consists of only one forward slash. Just use the equality check in this case.

s == '/'