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

**URL:** <https://www.ruby-forum.com/t/cant-get-eval-to-reference-1-2-etc/75459>\
**Category:** Ruby\
**Created:** [November 9, 2006, 11:56pm UTC](https://www.ruby-forum.com/t/cant-get-eval-to-reference-1-2-etc/75459 "2006-11-09T23:56:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![nwiger](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/dbc845/32.png) [@nwiger](https://www.ruby-forum.com/u/nwiger)\
**Post date:** [November 9, 2006, 11:56pm UTC](https://www.ruby-forum.com/t/cant-get-eval-to-reference-1-2-etc/75459/1 "2006-11-09T23:56:53Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![nwiger](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/dbc845/32.png) [@nwiger](https://www.ruby-forum.com/u/nwiger)\
**Post date:** [November 10, 2006, 12:10am UTC](https://www.ruby-forum.com/t/cant-get-eval-to-reference-1-2-etc/75459/2 "2006-11-10T00:10:55Z")

</div>

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
