Ruby字符串单引号和双引号的区别

Python012

Ruby字符串单引号和双引号的区别,第1张

??? Ruby的字符串对象生成有两种方式,字符串文字值加单引号或加双引号。

?

??? 两种方式主要区别在于构造文字量时,对字符串的处理次数不同。

?

??? 单引号时,Ruby对字符串值不做处理,里边是什么就是什么。

?

??? 双引号时,Ruby首先要查找文本中要替换的字符,即带反斜杠的字符,用二进制替换。最常见的就是\n;其次,这种方式下可以插入表达式#{...},那就要处理表达式,将其替换成具体的值。

一实例即可说明问题

@title="test"

p '<title>#{@title}</title>'

#原样输出

# =>"<title>\#{@title}</title>"

p "<title>#{@title}</title>"

#计算出变量的值,再变成字符串输出

# =>"<title>test</title>"

#内容亦可以进行字符串运算

p "<title>#{"this is "+@title}</title>"

# =>"<title>this is test</title>"

ruby的String类有一个方法叫chomp,用来去掉字符串末尾的\n或\r 例子这样 "hello".chomp #=>"hello" "hello\n".chomp #=>"hello" "hello\r\n".chomp #=>"hello" "hello\n\r".chomp #=>"hello\n" "hello\r".chomp #=>"hello"