2011-05-04 18 views
1

爲什麼我從這兩個投入有不同的結果?檢查給我\但只放

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\\ 

回答

2

Ruby的String.inspect轉義所有特殊字符,這就是爲什麼你SEEE 「\\」 與.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\\ 
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

你是正確的,但措辭是相反的 - 'puts'會按原樣輸出字符串(也就是說,所有的轉義字符都會在屏幕上被解析爲產生相應的字符),而'inspect'會跳過所有的轉義序列,以便它們在屏幕上顯示,而不會被解析。 – Laas 2011-05-04 08:18:47

+0

是的,在翻譯中丟失:)但我的想法是一樣的 – fl00r 2011-05-04 08:31:56

+0

當然。這就是爲什麼我沒有添加其他答案。 – Laas 2011-05-04 08:57:27