单引号字符串与双引号字符串中的反斜杠 [英] Backslashes in single quoted strings vs. double quoted strings

查看:326
本文介绍了单引号字符串与双引号字符串中的反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在双引号和单引号字符串的开头添加反斜杠+空格,则会得到不同的结果:

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.

是否有一些规则可以帮助解释Ruby中单引号字符串和双引号字符串如何处理反斜杠之间的根本区别?

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?

推荐答案

我将带您参考"

I'd refer you to "Ruby Programming/Strings" for a very concise yet comprehensive overview of the differences.

从参考文献:

puts "Betty's pie shop"

puts 'Betty\'s pie shop'

因为"Betty's"包含一个单引号,所以它与单引号相同,因此在第二行中,我们需要使用反斜杠来转义该单引号,以便Ruby理解该单引号位于字符串文字中而不是标记中字符串文字的结尾.反斜杠后跟单引号称为转义序列.

Because "Betty's" contains an apostrophe, which is the same character as the single quote, in the second line we need to use a backslash to escape the apostrophe so that Ruby understands that the apostrophe is in the string literal instead of marking the end of the string literal. The backslash followed by the single quote is called an escape sequence.

这篇关于单引号字符串与双引号字符串中的反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆