1 min read

TIL: Ruby Regex %r{}

Avoid escaping slashes with this macro

Forests of escape slashes in regex can be avoided using the %r{} macro.

Consider this:

url = 'https://foo.bar/'
match = url.match(/https:\/\/foo\.bar\//)

Ouch. My eyes. Better:

url = 'https://foo.bar/'
match = url.match(%r{http://foo\.bar/})

You no longer have to escape the / although you still have to escape the ..