The Ruby %r{ } expression

In a model there is a field

validates :image_file_name, :format => { :with => %r{\.(gif|jpg|jpeg|png)$}i

It looks pretty odd for me. I am aware that this is a regular expression. But I would like:

  • to know what exactly it means. Is %r{value} equal to /value/ ?
  • be able to replace it with normal Ruby regex operator /some regex/ or ~=. Is it possible?

Solution 1:

%r{} is equivalent to the /.../ notation, but allows you to have '/' in your regexp without having to escape them:

%r{/home/user}

is equivalent to:

/\/home\/user/

This is only a syntax commodity, for legibility.

Edit:

Note that you can use almost any non-alphabetic character pair instead of '{}'. These variants work just as well:

%r!/home/user!
%r'/home/user'
%r(/home/user)

Edit 2:

Note that the %r{}x variant ignores whitespace, making complex regexps more readable. Example from GitHub's Ruby style guide:

regexp = %r{
  start         # some text
  \s            # white space char
  (group)       # first group
  (?:alt1|alt2) # some alternation
  end
}x

Solution 2:

With %r, you could use any delimiters.

You could use %r{} or %r[] or %r!! etc.

The benefit of using other delimeters is that you don't need to escape the / used in normal regex literal.