Project

General

Profile

Actions

Bug #12636

closed

string.gsub(/([a-z](?=[A-Z._ ]))/, "#{$1} ") returns wrong result (possible C-string leak?)

Added by MikeCTM (Mike McFadden) almost 8 years ago. Updated over 7 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
[ruby-core:76610]

Description

Verified in Ruby 2.1, 2.2, and 2.3.

> "Hello.World".gsub(/([a-z](?=[A-Z._ ]))/, "#{$1} ")
=> "Hell .World"

^ wrong answer; it should be "Hello .World"

> "Hello.World".gsub(/([a-z](?=[A-Z._ ]))/, "#{$1} ")
=> "Hello .World"

^ running it a second time in the same IRB session now returns the correct result, however...

> "Help.World".gsub(/([a-z](?=[A-Z._ ]))/, "#{$1} ")
=> "Helo .World"

^ now the p turned into an o somehow? It's clearly retaining strings from the previous invocation and reusing them, but not updating every byte.

Here's the equivalent code in JavaScript, which returns the correct result every time:

"Hello.World".replace(/([a-z](?=[A-Z._ ]))/g, "$1 ")

Updated by jeremyevans0 (Jeremy Evans) almost 8 years ago

This isn't a bug, it's because "#{$1} " is evaluated before the call to gsub, using the results of the previous regexp match. You probably want to use '\1 ' instead.

Updated by nobu (Nobuyoshi Nakada) almost 8 years ago

  • Status changed from Open to Closed

Updated by usa (Usaku NAKAMURA) over 7 years ago

  • Status changed from Closed to Rejected
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0