Hacker News new | ask | show | jobs
by danso 4434 days ago
Something in my computer-science-student background feels unsettled when I can use a language for years and still learn new tricks (or often, that I've forgotten that I've learned) about common functionality such as string interpolation...but I do love a lot of Ruby's tricks.

    if path =~ %r{^/assets/mobile/img}
       ...
    end
I knew about `%r` but hadn't realized that it escapes forward-slashes while leaving other regex symbols intact. But with the previous explanation of `%q`, in which arbitrary delimiters can be used, it makes sense...curly braces simply replace `/` as the delimiter, and `/` simply retains its non-specialness in regex...saves me a lot of writing `Regex.escape("/path/to")`.

Another regex notation that I recently learned (elsewhere) and now love to abuse:

     "He is 32-years old"[/\d+/] # => "32"
    
as opposed to:

     "He is 32-years old".match(/\d+/)[0]
4 comments

The extension of that can also be handy and is often overlooked. Contrived example:

    "28 men are 32 years old"[/(\d+) (year|day|month)/, 1] # => "32"
This explanation of how %r works here is incorrect:

> I knew about `%r` but hadn't realized that it escapes forward-slashes while leaving other regex symbols intact.

The correct explanation can also be found in the next sentence of your comment:

> But with the previous explanation of `%q`, in which arbitrary delimiters can be used, it makes sense...curly braces simply replace `/` as the delimiter, and `/` simply retains its non-specialness in regex.

Not sure arbitrary regex delimiters can be counted as one of "Ruby's tricks" given they've been implemented in sed for maybe 4 decades?
You can also use

   Regexp.new("/foo/bar")
to achieve the desired result but the %r{} shortcut is handier.