Question

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)

Was it helpful?

Solution

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}`

OTHER TIPS

`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 is right, but there is no need to assemble the args piecewise:

directory = '/Volumes/Omg a space/'
system('/bin/ls', directory)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top