Ruby Backquotes

I learnt a useful but very simple thing with Ruby today. Using backquotes, you can return the standard output of running cmd in a subshell.

e.g.

> `date`
> "Wed Nov 22 19:11:32 GMT 2006"

Now think about how you could use this in Rails to display the subversion revision of your web application. Simple, using YAML and the svn info command.

The svn info command returns the following output.

Path: .
URL: http://myrepository.tld/svn/projects
Repository Root: http://myrepository.tld/svn/projects
Repository UUID: bab91cb8-3837-db11-9351-0014220fd224
Revision: 143
Node Kind: directory Schedule: normal
Last Changed Author: goatley
Last Changed Rev: 143
Last Changed Date: 2006-11-22 17:57:18 +0000 (Wed, 22 Nov 2006)

This looks like YAML to me, so we can load the output into the YAML object.

> REVISION = YAML.load(`svn info`)['Revision']
> 143

Very useful!

2 Responses to “Ruby Backquotes”

  1. John H Says:

    Isn’t that one of Ruby’s holdovers from Perl? Although I like the concept, I’ve never liked actually using the backquotes, mostly because they’re too easy to get confused with the normal single quote characters. I think Perl had another way to do the same thing, but without using the backquotes. I hope Ruby has. Meanwhile, just to show how non-partisan I am, I’ve spent several hours this week actively trying to learn Python.

  2. Garth Says:

    Ruby has an alternative to backquotes, you can use the x syntax %x{ … }.

    Python is interesting, it reminds me of Basic in a way. I started to learn Ruby because of the Rails framework. Python is a language I’d learn if I started to use Django. Some friends of mine continually rave on about the Python language, and of course, it’s the preferred language of Ubuntu.

Leave a Reply