views:

426

answers:

3

I would like to execute an OS command from my ruby script but I want to add an argument from a ruby variable.

I know that's possible by using keyword system like that :

#!/usr/bin/env ruby
directory = '/home/paulgreg/'
system 'ls ' + directory

but is that possible by using the "backquotes or backticks syntax" ? (I mean by using that syntax : ls)

+3  A: 

No, that will just concatenate the output from ls and the contents of directory.

But you can do this:

#!/usr/bin/env ruby
directory = '/home/paulgreg/'
`ls #{directory}`
Jordi Bunster
+3  A: 
`ls #{directory}`

isn't very safe because you're going to run into problems with path names that have spaces in them.

It's safer to do something like this:

directory = '/home/paulgreg/'

args = []
args << "/bin/ls"
args << directory

system(*args)
Nick Brosnahan
A: 

Nick is right, but there is no need to assemble the args piecewise:

directory = '/Volumes/Omg a space/'
system('/bin/ls', directory)
0124816