# Gsub producing different results running the same code

**URL:** <https://meta.discourse.org/t/gsub-producing-different-results-running-the-same-code/203837>\
**Category:** Product Support\
**Created:** [September 17, 2021, 5:17pm UTC](https://meta.discourse.org/t/gsub-producing-different-results-running-the-same-code/203837 "2021-09-17T17:17:52Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![david](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/david/32/157490_2.png) [@david](https://meta.discourse.org/u/david)\
**Post date:** [September 17, 2021, 8:43pm UTC](https://meta.discourse.org/t/gsub-producing-different-results-running-the-same-code/203837/3 "2021-09-17T20:43:49Z")

</div>

Variables like `$1` are populated **after** a regex match is performed. Simplifying your example a little:

```ruby
s.gsub('original(value)', "replacement#{$1}")

```

The `"replacement#{$1}"` expression is evaluated **before** the gsub function is called. So `$1` will be leftover from some previous regex task. (That’s why your second attempt works - it takes `$1` from the first attempt)

There are a couple of options to solve this problem. [gsub](https://apidock.com/ruby/String/gsub) has lots of different functionalities.

My preference would be to pass a block to gsub. The block is evaluated after the regex has been matched, so `$1` will work as you expect:

```ruby
s.gsub('original(value)') { |match| "replacement#{$1}" }

```

Or you can use the ‘backreference’ feature of gsub. I’m not a fan of this syntax, but it does work. Rather than using `"replacement#{$1}"`, you use `'replacement\1'` (or `\2`, or `\3`, etc.)

```ruby
s.gsub('original(value)', 'replacement\1')

```

---

_[View the full topic](https://meta.discourse.org/t/gsub-producing-different-results-running-the-same-code/203837)._
