Forum: Ruby HOWTO Use Veriables inside of Regexp and Commands?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Karl B. (Guest)
on 2006-04-06 04:11

I've just started using Ruby and am LOVING IT! :D

For my job I need to do allot of shell scripting but have been getting
very annoyed at its limitations.

So I am now looking to Ruby to replace it. The thing is I need to be
able to run a command say "ls" with a variable say "directory". Heres an
example of what I would do in shell script.


ls $directory

Now in Ruby I have to use the backquotes for commands right? So if I
create a variable directory in Ruby how do I get it's contents to be
executed in the command or evaluated in a regular expression?

For example:

directory = "/tmp"

puts `ls directory`
puts /directory/

I know the above is wrong and both will just evaluate the word directory
not the variables contents. So how do I get the contents in there?

Thank you very much for you help.
Keith S. (Guest)
on 2006-04-06 04:30
(Received via mailing list)
Have you tried just using

Dir.entries('/path/to/dir').each {|entry| puts entry}?
Karl B. (Guest)
on 2006-04-06 04:52
Nope but unfortunately that only gives me solution to one situation :/

There are allot of other times I'll want to run a different command with
varying input.

Is there no escape character or anything that can bee used?

Also on these forums wheres the reply button? I Could only find the
reply with quote one?
Craig K. (Guest)
on 2006-04-06 05:40
(Received via mailing list)
To answer the original question, you can embedded any variables or
expressions in #{exp}. In your example, you can say:

directory = '/tmp'
puts `ls #{directory}`
if '/tmp/junk' =~ /^#{directory}/

If you are interested in getting directory entries, Keith's excellent
suggestion is what you should consider.

Hope it helps!
Karl B. (Guest)
on 2006-04-06 06:04
Awesome thanks to you both :)

Craig your answer is exactly what I was looking for :)

And thanks to you Keith I have another very interesting class to look at
Logan C. (Guest)
on 2006-04-06 22:20
(Received via mailing list)
On Apr 5, 2006, at 10:04 PM, Karl Bennett wrote:

Note that puts `command` is sort of redundant, if you don' want to
store the results in the string

system("command") will send the output to the standard output,
without allocating a big string. Other methods you may want to look
into are IO.popen .
This topic is locked and can not be replied to.