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 this possible?
%r{}is equivalent to the/.../notation, but allows you to have ‘/’ in your regexp without having to escape them:is equivalent to:
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:
Edit 2:
Note that the
%r{}xvariant ignores whitespace, making complex regexps more readable. Example from GitHub’s Ruby style guide: