你知道在ruby中使用双引号而不是单引号会在ruby 1.8和1.9中以任何有意义的方式降低性能.
所以,如果我输入
question = 'my question'
Run Code Online (Sandbox Code Playgroud)
比它快吗?
question = "my question"
Run Code Online (Sandbox Code Playgroud)
我想ruby试图弄清楚当遇到双引号时是否需要对某些东西进行评估,并且可能花费一些周期来做这件事.
我有一个阵列..
[1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
我想要一个包含由换行符分隔的所有元素的字符串.
1
2
3
4
Run Code Online (Sandbox Code Playgroud)
但是当我尝试时,[1,2,3,4].join("\n")我得到了
1\n2\n3\n4
Run Code Online (Sandbox Code Playgroud)
我觉得有一个明显的答案,但我找不到它!
所以我正在关注这个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?
我理解Ruby中单引号和双引号之间的功能差异,但我想知道人们在两者之间有何不同的具体原因.在我看来,似乎你应该总是使用双引号,而不是考虑它.
我在研究这个主题时读过的一些理由......
除非需要双引号,否则请使用单引号.
单引号的性能优势非常非常小.
还有其他有趣的想法吗?(或者这可能是一个自由的例子,或者Ruby为没有一个正确的方式做某事而敞开大门......)