Regular exressions and arguments

R

Rick Jones

This should be (and probably will be) a simple answer, but if I have the
very basic program of:

#!/usr/bin/ruby

require

arg = ARGV[0]
regex = /"#{arg}"/
regex1 = /Test/

a = "this is a Test"

if regex =~ a
puts "test works"
else
puts "test isn't working"
end



With this code, if i inputs ./filename 'Test', how can i get the regex
to be correct? I can only think of using the "#{}" to put this inside
the expression, but this puts the parenthesis around it...
 
R

Rick Jones

Should have just waited a little longer... figured it out... needed to
use the a = Regex.new(ARGV[0]) command to make it work... Thanks any way
every one.
 
J

Jesús Gabriel y Galán

Should have just waited a little longer... figured it out... needed to
use the a = Regex.new(ARGV[0]) command to make it work... Thanks any way
every one.

You can also use the regex literal, but you need to lose the double quotes.
Check this:

irb(main):001:0> a = "Test"
=> "Test"
irb(main):002:0> re = /#{a}/
=> /Test/
irb(main):003:0> re = /"#{a}"/
=> /"Test"/

Hope this helps,

Jesus.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,181
Messages
2,570,970
Members
47,537
Latest member
BellCorone

Latest Threads

Top