Ruby - 单引号和双引号之间的区别是什么?

时间:2012-10-31 13:31:37

标签: ruby

所以我正在关注这个Ruby教程:Learn Ruby the Hard Way.

在练习16(上面链接)中,您编写了一个将行写入文件的脚本。相关代码是:

print "line 1: "; line1 = STDIN.gets.chomp()
print "line 2: "; line2 = STDIN.gets.chomp()
print "line 3: "; line3 = STDIN.gets.chomp()

puts "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

然而,作为我的懒惰流浪汉,我最初在最后六行中使用单引号键入示例,而不是教程告诉您使用的双引号。

这对文件有影响。当我使用单引号时,文件看起来像这样:

this is line 1\nthis is line 2\nthis is line 3

将这些引号切换为双引号后,文件按预期显示:

this is line 1
this is line 2
this is line 3

有人可以告诉我为什么会这样吗?单引号字符串是否会忽略\n\t等转义字符?

1 个答案:

答案 0 :(得分:17)

是的,单引号字符串不处理ASCII转义码,也不进行字符串插值。

name = 'Joe'
greeting = 'Hello, #{name}' # this won't produce "Hello, Joe" 
相关问题