Ruby Backtick

One of my favorite things about Ruby is how it handles operator overloading.  For example, to overload (+) on a class, you can just define a specially-named method:

class John
  def +(other)
    puts "so you want to add #{other} to me, eh?"
  end
end

And accessing it looks something like:

John.new + 1

Another case of these that I think is fun, but that we don’t think of as a method too often, is the backtick operator.  You can redefine backtick just like anything else:

def `(str)
  puts str
end

which will print anything contained in backticks instead of executing it:

`hello world!`

BONUS FACT: Did you know the proper name for backtick is the grave accent?

Tags: ,

  • http://joelcox.nl/ Joël Cox

    My Ruby knowledge is limited, but shouldn’t it be “which will print anything _after_ a backtick instead of executing it”? E.g. “John.new ` hello world” result in `hello world`

    • http://seejohncode.com/ John Crepezzi

      Hey Joël,

      The backtick operator is special in that sense, since it surrounds its argument, instead of just preceding it.

      You can play with it in `irb` by just typing:

      1.9.2p290 :001 > def `(hi); puts hi; end

      and then using it like:

      `hello world`

    • http://joelcox.nl/ Joël Cox

      Ah, thanks.