为什么我的两个投注都有不同的结果?
test_string = "C:/Program Files/TestPro/TestPro Automation Framework/"
puts test_string.gsub("/","\\\\")
#result is : C:\Program Files\TestPro\TestPro Automation Framework\
puts
puts test_string.gsub("/","\\\\") .inspect
#result as desired : C:\\Program Files\\TestPro\\TestPro Automation Framework\\
答案 0 :(得分:2)
puts
将返回第一个斜杠作为转义符号。 Inspect不会触发转义斜杠,因此它会显示原始字符串。
string = "\\Hello World!\\"
puts string
#=> "\Hello World!\"
string
#=> "\\Hello World!\\"
因此,如果您尝试这样做,它将起作用:
puts "I am in \"Dog Bar\" now"
#=> "I am in "Dog Bar" now"
"I am in \"Dog Bar\" now"
#=> "I am in \"Dog Bar\" now"
"I am in "Dog Bar" now"
#=> SyntaxError: compile error
答案 1 :(得分:2)
Ruby的String.inspect转义所有特殊字符,这就是为什么你会看到“\\
”与.inspect
请参见String.inspect source此处
if (c == '"'|| c == '\\' ||
(c == '#' &&
p < pend &&
MBCLEN_CHARFOUND_P(rb_enc_precise_mbclen(p,pend,enc)) &&
(cc = rb_enc_codepoint(p,pend,enc),
(cc == '$' || cc == '@' || cc == '{')))) {
if (p - n > prev) str_buf_cat(result, prev, p - n - prev);
str_buf_cat2(result, "\\");
prev = p - n;
continue;
}
基本上,if c == '\'
,将“\
”连接到它,因此它变为“\\
”
如果你想双击反斜杠,你需要尝试
test_string = "C:/Program Files/TestPro/TestPro Automation Framework/"
puts test_string.gsub("/","\\\\\\\\")
#C:\\Program Files\\TestPro\\TestPro Automation Framework\\