Project

General

Profile

Actions

Backport #7354

closed

String#gsub not working as expected

Added by moonr0ck (Ilya Ostrovskiy) over 11 years ago. Updated over 11 years ago.

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

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* "#{RUBY_VERSION}p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})"
=> "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* "#{RUBY_VERSION}p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})"
=> "1.9.3p286 (2012-10-12)"

=end

Updated by moonr0ck (Ilya Ostrovskiy) over 11 years 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"

Updated by naruse (Yui NARUSE) over 11 years 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")

Updated by moonr0ck (Ilya Ostrovskiy) over 11 years ago

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

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0