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

所以我正在关注这个Ruby教程: 以艰难的方式学习Ruby。

在练习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等转义字符?

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

 name = 'Joe' greeting = 'Hello, #{name}' # this won't produce "Hello, Joe"