Can't get eval to reference $1, $2, etc

N

Nate Wiger

Ok, so I have this array of pairs that control file movements, for
organizing directory trees. It looks something like this:

rules = [
['(.+).tgz', 'tars/$1'],
['(.+)-(.+).war', '$1/webapps/$2'],
# and so on...
]

Then, I want to iterate through these, capturing the regex matches and
using them in the paths on the right side of the hash. I have something
like this:

file = 'abc.tgz' # just for example
dest = ''
rules.each do |row|
if file =~ %r{^#{row[0]}$}
eval "dest = \"#{row[1]}\"" # XXX broken: want to ref matches
break
end
end
puts dest # "tars/$1", instead of "tars/abc"


The problem is, I can't get the matches to show up inside the eval. I've
tried %Q, different quote combinations, etc. Anyone know a way to make
this work?

Thanks,
Nate


P.S. Ruby 1.8.4 on CentOS 4
 
N

Nate Wiger

Answered my own question (of course)... here's a way to do this by using
sub instead of match/eval, which is much safer too:

path = file.dup
rules.each do |row|
dest = row[1] || ''
dest.gsub!('$','\\') # allow $Perl or \Sed markers
if path.sub!(%r{^#{row[0]}$}, dest)
return path
end
end

-Nate
 

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

Forum statistics

Threads
474,218
Messages
2,571,124
Members
47,728
Latest member
SusanGsc94

Latest Threads

Top