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

Python018

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"

(1)puts会识别双引号内的转义符,并自动换行

(2)p不会识别双引号内的转义符,并自动换行

(3)print会识别双引号内的转义符,不自动换行

点击(此处)折叠或打开

irb(main):003:0>puts "a", "\nb"

a

b

=>nil

irb(main):004:0>p "a", "\nb"

"a"

"\nb"

=>nil

irb(main):005:0>print "a", "\nb"

a

b=>nil