If I run this code:
"Retailer Staff $5.60".gsub(/.*\$(\d+(\.\d+)?).*/, $1)
# => 5.60
and then I change the value to:
"Retailer Staff $5".gsub(/.*\$(\d+(\.\d+)?).*/, $1)
# => 5.60
the answer stays at 5.60
. Then, if I run the same line again, I get:
"Retailer Staff $5".gsub(/.*\$(\d+(\.\d+)?).*/, $1)
# => 5
What's happening? Why would the same code run twice give two answers? Is gsub
caching something?
I believe this is happening because $1
actually is a global reference to the first capturing group found in the last regular expression that was processed: ruby 2.4 docs. So in your case you probably had already tested the regex and matched on "5.60". Here is an annotated snippet that I ran in ruby 2.0:
# Since no regex has executed yet $1 is nil
irb(main):001:0> "Retailer Staff $5.60".gsub(/.*\$(\d+(\.\d+)?).*/, $1)
TypeError: no implicit conversion of nil into String
from (irb):1:in 'gsub'
from (irb):1
from /usr/bin/irb:12:in '<main>'
irb(main):002:0> "Retailer Staff $5.60".gsub(/.*\$(\d+(\.\d+)?).*/, 'some value')
=> "some value"
irb(main):003:0> $1 # Now we have executed a regex so $1 is set
=> "5.60"
irb(main):004:0> "Retailer Staff $5.60".gsub(/.*\$(\d+(\.\d+)?).*/, $1)
=> "5.60"
irb(main):005:0> $1 # This is still the same value because we matched the same string
=> "5.60"
irb(main):006:0> "Retailer Staff $5".gsub(/.*\$(\d+(\.\d+)?).*/, $1)
=> "5.60"
irb(main):007:0> $1 # Now we have matched the 5 so $1 has the new value
=> "5"
irb(main):008:0> "Retailer Staff $5".gsub(/.*\$(\d+(\.\d+)?).*/, $1)
=> "5"
irb(main):009:0> $1
=> "5"