[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

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

Nate Wiger

11/9/2006 10:56:00 PM

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


1 Answer

Nate Wiger

11/9/2006 11:09:00 PM

0

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