This instance method added to the String class returns a copy of the
receiver with occurrences of \ replaced with \, and occurrences of ’
replaced with ':
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:
But I would have thought that three would work:
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?