Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

ruby - Backslashes in single quoted strings vs. double quoted strings

If I add a backslash+space to the start of double and single quoted strings, I get different results:

" text"
' text' 

In the output for the double quoted string I see only a space.
In the output for the single quoted string I see backslash+space.

What's happening there? Is this because ' ' is interpreted as a special character in the double quote string but in the single quoted string the characters are preserved as is?

If I change the strings to this, I see the same output, namely a single slash followed by a space and then the text:

"\ text"
'\ text' 

In both cases the backslash is escaped. I'm confused why they work the same way in this situation.

Is there some rule that would help to explain the fundamental difference between how single quoted strings and double quoted strings handle backslashes in Ruby?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Double-quoted strings support the full range of escape sequences, as shown below:

  • a Bell/alert (0x07)
  • Backspace (0x08)
  • e Escape (0x1b)
  • f Formford (0x0c)
  • Newline (0x0a)
  • Return (0x0d)
  • s Space (0x20)
  • Tab (0x09)
  • v Vertical tab (0x0b)

For single-quoted strings, two consecutive backslashes are replaced by a single backslash, and a backslash followed by a single quote becomes a single quote:

'escape using ""' -> escape using ""
'That's right'     -> That's right

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...