inspect gives me \\ but put only \
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
精彩评论