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

Nek*_*oru 12 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")
Run Code Online (Sandbox Code Playgroud)

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

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

this is line 1\nthis is line 2\nthis is line 3
Run Code Online (Sandbox Code Playgroud)

将这些引号切换为双引号后,该文件看起来像预期的那样:

this is line 1
this is line 2
this is line 3
Run Code Online (Sandbox Code Playgroud)

有人能告诉我究竟是为什么吗?单引号字符串只是忽略转义字符,如\n\t

Ser*_*sev 17

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

name = 'Joe'
greeting = 'Hello, #{name}' # this won't produce "Hello, Joe" 
Run Code Online (Sandbox Code Playgroud)