2012-10-31 139 views
11

所以我遵循這個Ruby教程:Learn Ruby the Hard Way.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

+0

是的,你是正確的 –

+0

*真的*懶惰的人不鍵入代碼,他們複製/粘貼。 :) –

+1

我很驚訝,有一個教程,你打開文件並寫入他們不會花時間沿途解釋字符串如何工作。 –

回答

16

是的,單引號字符串不會處理ASCII轉義碼,並且不會進行字符串插值。

name = 'Joe' 
greeting = 'Hello, #{name}' # this won't produce "Hello, Joe" 
相關問題