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

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
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?


P.S. Ruby 1.8.4 on CentOS 4

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


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs