问题描述
所以我正在学习这个 Ruby 教程:艰难地学习 Ruby.
So I'm following this Ruby tutorial: Learn Ruby the Hard Way.
在练习 16(上面链接)中,您编写了一个将行写入文件的脚本.相关代码为:
In exercise 16 (linked above), you write a script that writes lines to a file. The relevant code is:
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")
然而,作为一个懒惰的流浪汉,我最初在最后六行中使用单引号输入示例,而不是教程告诉您使用的双引号.
However, being the lazy bum that I am, I originally typed in the example using single quotes in the last six lines, instead of the double quotes the tutorial tells you to use.
这对文件有影响.当我使用单引号时,文件看起来像这样:
This had an effect on the file. When I used single quotes, the file looked like this:
this is line 1\nthis is line 2\nthis is line 3
将这些引号转换为双引号后,文件看起来如预期:
After switching those quotes to double-quotes, the file looked as expected:
this is line 1
this is line 2
this is line 3
谁能告诉我这是为什么?单引号字符串是否会忽略诸如 \n
或 \t
之类的转义字符?
Can someone tell me exactly why that is? Do single-quoted strings just ignore escape characters like \n
or \t
?
推荐答案
是的,单引号字符串不处理 ASCII 转义码,也不进行字符串插值.
Yes, single-quoted strings don't process ASCII escape codes and they don't do string interpolation.
name = 'Joe'
greeting = 'Hello, #{name}' # this won't produce "Hello, Joe"
这篇关于Ruby - 单引号和双引号有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!