开发者

inspect gives me \\ but put only \

开发者 https://www.devze.com 2023-03-03 06:03 出处:网络
why do I have different results from both puts? test_string = \"C:/Program Files/TestPro/TestPro Automation Framework/\"

why do I have different results from both puts?

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 Automat开发者_开发问答ion Framework\\


Ruby's String.inspect escape all special characters, thats why you seee "\\" with .inspect

See String.inspect source here

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;
}

basically, if c == '\', concatenate "\" to it, so it became "\\"

If you want double escape the backslash, you need to try with

test_string = "C:/Program Files/TestPro/TestPro Automation Framework/"
puts test_string.gsub("/","\\\\\\\\")

#C:\\Program Files\\TestPro\\TestPro Automation Framework\\


puts will return first slashes as an escape symbol. Inspect won't trigger escape slashes, so it shows original string.

string = "\\Hello World!\\"
puts string
#=> "\Hello World!\"
string
#=> "\\Hello World!\\"

So if you will try this it will work:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消