Backport #7354

String#gsub not working as expected

Added by Ilya Ostrovskiy over 1 year ago. Updated over 1 year ago.

[ruby-core:49360]
Status:Rejected
Priority:Normal
Assignee:-

Description

=begin

Windows 7, with Ruby 1.9.3p327, originally found in 1.9.3.p194
irb(main):001:0> filename = "test.txt"
=> "test.txt"
irb(main):002:0> suffix = "-suffix"
=> "-suffix"
irb(main):003:0> filename.gsub(/.+(..+)$/, "#{$1}#{suffix}#{$2}")
=> "-suffix"
irb(main):004:0> # ^ that doesn't look right
irb(main):005:0* # now if i add some spaces to the replacement string
irb(main):006:0* # it will work like it should (with the spaces)
irb(main):007:0* filename.gsub(/.+(..+)$/, "#{$1}#{suffix} #{$2}")
=> "test-suffix .txt"
irb(main):008:0> # and if i run the original it will work fine now
irb(main):009:0* filename.gsub(/.+(..+)$/, "#{$1}#{suffix}#{$2}")
=> "test-suffix.txt"
irb(main):010:0> # Running Windows 7, installed using RubyInstaller.org
irb(main):011:0* "#{RUBYVERSION}p#{RUBYPATCHLEVEL} (#{RUBYRELEASEDATE})"
=> "1.9.3p327 (2012-11-10)"

Arch Linux with Ruby 1.9.3.p286
irb(main):001:0> filename = "test.txt"
=> "test.txt"
irb(main):002:0> suffix = "-suffix"
=> "-suffix"
irb(main):003:0> filename.gsub(/.+(..+)$/, "#{$1}#{suffix}#{$2}")
=> "-suffix"
irb(main):004:0> # ^ that's not right
irb(main):005:0* # adding spaces works just like in windows
irb(main):006:0* filename.gsub(/.+(..+)$/, "#{$1}#{suffix} #{$2}")
=> "test-suffix .txt"
irb(main):007:0> # and removing the space gives the expected result now
irb(main):008:0* filename.gsub(/.+(..+)$/, "#{$1}#{suffix}#{$2}")
=> "test-suffix.txt"
irb(main):009:0> # Reproduced on Arch Linux
irb(main):010:0* "#{RUBYVERSION}p#{RUBYPATCHLEVEL} (#{RUBYRELEASEDATE})"
=> "1.9.3p286 (2012-10-12)"

=end

History

#1 Updated by Ilya Ostrovskiy over 1 year ago

It appears the spaces have no effect, and simply re-running the gsub is sufficient to get the expected result.

irb(main):001:0> filename = "test.txt"
=> "test.txt"
irb(main):002:0> suffix = "-suffix"
=> "-suffix"
irb(main):003:0> filename.gsub(/^(.+)(\..+)$/, "#{$1}#{suffix}#{$2}")
=> "-suffix"
irb(main):004:0> filename.gsub(/^(.+)(\..+)$/, "#{$1}#{suffix}#{$2}")
=> "test-suffix.txt"

#2 Updated by Yui NARUSE over 1 year ago

  • Status changed from Open to Rejected

Embeded $1 is evaled before gsub runs.

You should write it as
filename.gsub(/.+(..+)$/){"#{$1}#{suffix}#{$2}"}
or
filename.gsub(/.+(..+)$/, "\1#{suffix}\2")

#3 Updated by Ilya Ostrovskiy over 1 year ago

Thank you! :) I had a feeling that perhaps it wasn't a bug and I was just doing something wrong.

Also available in: Atom PDF