Weird backslash substitution in Ruby

前端 未结 5 1617
时光说笑
时光说笑 2020-11-28 09:19

I don\'t understand this Ruby code:

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

>> puts \'\\\\ <- 2x a, because 2 bac         


        
5条回答
  •  鱼传尺愫
    2020-11-28 10:07

    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 <

提交回复
热议问题