HOWTO Use Veriables inside of Regexp and Commands?

Hi,

I’ve just started using Ruby and am LOVING IT! :smiley:

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.

$directory="/tmp"

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.

Have you tried just using

Dir.entries(’/path/to/dir’).each {|entry| puts entry}?

Nope but unfortunately that only gives me solution to one situation :confused:

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?

Awesome thanks to you both :slight_smile:

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

And thanks to you Keith I have another very interesting class to look at
:wink:

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!

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 .