From: Greg Hurrell Date: 2007-02-22T02:55:09+09:00 Subject: Weird behaviour escaping special characters in a string This instance method added to the String class returns a copy of the receiver with occurrences of \ replaced with \\, and occurrences of ' replaced with \': class String def to_source_string gsub(/(\\|')/, '\\\\\1') end end The idea is that it will give you a string that you can write out a Ruby file that will later print the string. For, example, let's take the string, foo (3 characters): "puts '" + "foo".to_source_string + "'" # puts 'foo' Or a string with special characters in it like 'foo' (5 characters, including enclosing single quotes): "puts '" + "'foo'".to_source_string + "'" # puts '\'foo\'' My RSpec specs and experimentation in irb confirm that the method works but I am at a loss to explain one thing: Why do I need so many backslashes in my replacement expression? There are five slashes in the replacement expression: gsub(/(\\|')/, '\\\\\1') But I would have thought that three would work: gsub(/(\\|')/, '\\\1') I basically want to replace "whatever is found in the pattern" with a backslash (\\) followed by "whatever was found" (\1); so that's three slashes. But with only three slashes Ruby gives me \1foo\1 instead of \'foo\'. Four slashes produces the same result. Five slashes and suddenly everything works (funnily enough, six slashes also works). Two slashes and one slash have no effect (no escaping is performed). I've got working code so it's not a huge problem, but my curiosity is piqued. What's going on here that I don't understand? Cheers, Greg