From: Brian Candler Date: 2010-09-26T07:08:13+09:00 Subject: Re: bug in gsub(?) Tiziano Merzi wrote: > I have found this bug(?) in gsub http://www.catb.org/~esr/faqs/smart-questions.html#id382249 > puts "\\:{}=#~".gsub(/([\\\:\~\=\#\{\}])/, '\\ \1') > => \ \\ :\ {\ }\ =\ #\ ~ OK > > but > > puts "\\:{}=#~".gsub(/([\\\:\~\=\#\{\}])/, '\\\1') > => \1\1\1\1\1\1\1 > > Any idea? puts "a".gsub(/a/, '\\\\') # i.e. two backslashes => \ That is, in a replacement string, if you backslash-escape a backslash you get a single backslash. That allows you to have literally \1 if that's what you need. So a literal backslash is \\, and the first capture is \1 So what you want is \\\1, to get a backslash followed by the first capture. However, that is represented in a string literal as '\\\\\\1' (which generates a 4 character string) because a string literal also has backslash escaping. >> '\\\\\\1'.size => 4 >> puts "\\:{}=#~".gsub(/([\\\:\~\=\#\{\}])/, '\\\\\\1') \\\:\{\}\=\#\~ => nil Take a suggestion from me: save your sanity and use the block form instead :-) >> puts "\\:{}=#~".gsub(/([\\\:\~\=\#\{\}])/) { "\\#{$1}" } \\\:\{\}\=\#\~ => nil -- Posted via http://www.ruby-forum.com/.