Overriding the Backtick in Ruby

I’ve been planning this post for a long time, and Magnus Holme’s recent article on overriding unary operators gives me the perfect lead-in.

Ruby has great syntax sugar for quoting strings. You’ve got your single- and double-quotes; you’ve got slashes for Regexps and you’ve got a whole menagerie of %-quotes, such as %r for regular expressions: %r(/.*/).

But Ruby is a bit uptight about its quotes; if there’s a special kind of quoting you want to do that Matz didn’t think of, there’s no way to add it to the language. For instance, what if you wanted a way to quote URIs and have them be immediately parsed into URI objects, something like this:

We can’t do anything like that… can we?

Well, maybe we can. You know how backtick quoting works, right? Put a string in backticks and you get the result of that string evaluated as a shell command:

What you might not know is that the backtick, unlike other quotes, is technically an operator defined in Kernel. And what is defined in Kernel can be overridden:

And there you have it – your own custom backtick quotes.

Is this a good idea? Probably not. I certainly don’t recommend overriding the backticks at the root level as I’m doing here – this is a technique best limited to certain DSL contexts. But for better or for worse, now you know that even (some) quotes are overridable in Ruby.