Alex Rivera | Logout

Weird backslash substitution in Ruby

Asked 2009-10-09T06:59:14.027
33

I don't understand this Ruby code:

>> puts '\\ <- single backslash'
# \ <- single backslash

>> puts '\\ <- 2x a, because 2 backslashes get replaced'.sub(/\\/, 'aa')
# aa <- 2x a, because two backslashes get replaced

so far, all as expected. but if we search for 1 with /\\/, and replace with 2, encoded by '\\\\', why do we get this:

>> puts '\\ <- only 1 ... replace 1 with 2'.sub(/\\/, '\\\\')
# \ <- only 1 backslash, even though we replace 1 with 2

and then, when we encode 3 with '\\\\\\', we only get 2:

>> puts '\\ <- only 2 ... 1 with 3'.sub(/\\/, '\\\\\\')
# \\ <- 2 backslashes, even though we replace 1 with 3

anyone able to understand why a backslash gets swallowed in the replacement string? this happens on 1.8 and 1.9.

Edit
Report

1 Answer

18

This is an issue because backslash (\) serves as an escape character for Regexps and Strings. You could do use the special variable \& to reduce the number backslashes in the gsub replacement string.

foo.gsub(/\\/,'\&\&\&') #for some string foo replace each \ with \\\

EDIT: I should mention that the value of \& is from a Regexp match, in this case a single backslash.

Also, I thought that there was a special way to create a string that disabled the escape character, but apparently not. None of these will produce two slashes:

puts "\\"
puts '\\'
puts %q{\\}
puts %Q{\\}
puts """\\"""
puts '''\\'''
puts <<EOF
\\
EOF  
answered 2009-10-09T07:11:52.733

Your Answer