Oct
7Tip: Running command line / shell commands in Ruby using %x
7
Posted: 7th October 2007
Tags: Ruby on Rails, tips
Posted in Ruby on Rails
Comments: 5 Comments »
I thought I would post a very quick tip on how to execute a command line / shell command with Ruby. There are several ways to run command lines / shell commands in Ruby as discussed by Jay Fields however by far the most useful of these is the %x command, as follows:
- @whois = %x[whois clockobj.co.uk]
And what is important and not mentioned by Jay is the fact that you can pass parameters into %x[] as follows:
- dom = ‘clockobj.co.uk‘
- @whois = %x[whois #\{dom\}]




Hey there, Thought I’d let you know there are a few different ways - I didn’t know about %x, but it is very similar to the backtick (`). Example: `dig yahoo.com` `dig #{domain}` Double quote rules apply. Of course, I might start adopting the %x[] format for readability - unless you are using an IDE or VIM (my choice) with syntax highlighting, backticks are hard to spot.