Why does my Ruby string show the escape character backslash ('\') twice?

时间:2015-12-10 01:59:03

标签: ruby string escaping

I'm using \.br\ as delimiter:

[10, 20, 30].join('\.br\\')

expected result:

"10\.br\20\.br\30"

what is actually returned:

"10\\.br\\20\\.br\\30"

I added escape for the backslash, how could I get the expected result?

1 个答案:

答案 0 :(得分:3)

I think you'll find that the backslashes are not in fact doubled in the string.
To check, instead of printing it using p (which uses String#inspect) just print it using puts.

When the string is inspected it uses double-quotes, and tries to produce a version of the string that you can copy and paste in to Ruby to get the same string - so it needs to double up the backslash characters.