BrainLikeADullPencil
BrainLikeADullPencil

Reputation: 11673

backtick operator

The code below, taken from a RubyTapas screencast, prints out a Cowsays message to the terminal. The class has two methods, say and also a backtick method that accepts the url as parameter. It doesn't work without the backtick method, but I don't understand when/how the backtick method is used to print out the cowsays message, because the backtick method is never called. It appears (to me) that you just need to call the say method, like so Cowsays.new.say "Hello, StackOverflow". Can you explain how the backtick method gets called in this code?

 ______________________
< Hello, StackOverflow >
 ----------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

code

require 'net/http'
require 'cgi'

class Cowsays
  def `(url)
    URI.parse(url)
  end

  def say(message)
    message = CGI.escape(message)
    Net::HTTP.get_print(`http://www.cowsays.com/cowsay?message=#{message}`)
  end
end

Cowsays.new.say "Hello, StackOverflow"

Upvotes: 2

Views: 1227

Answers (2)

doesterr
doesterr

Reputation: 3965

The trick that is shown here is, that you can overwrite the backtick operator.

So, instead of writing:

Net::HTTP.get_print(URI.parse("http://www.cowsays.com/cowsay?message=#{message}"))

You can overwrite the backtick and use

Net::HTTP.get_print(`http://www.cowsays.com/cowsay?message=#{message}`)

instead.

As already mentioned in the screencast and the comments here - this is just a trick, and it's not advised to actually use it :)

Upvotes: 2

tadman
tadman

Reputation: 211720

This should be regular quotes like ' and not backtick. Backtick is used to execute shell commands and returns the results.

For example, to get a listing of files:

files = `ls`

This is apparently passed through to the backtick method in Kernel which you can over-ride if you want. I've never seen this done before and seems like an exceptionally bad idea to do in a production application.

Upvotes: 0

Related Questions