12

だから私はこの Ruby チュートリアルに従っています: Learn Ruby the Hard Way.

演習 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")

ただし、私は怠け者なので、チュートリアルで使用するように指示されている二重引用符の代わりに、最初に最後の 6 行で単一引用符を使用して例を入力しました。

これはファイルに影響を与えました。一重引用符を使用すると、ファイルは次のようになります。

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?

4

1 に答える 1

17

はい、一重引用符で囲まれた文字列はASCIIエスケープコードを処理せず、文字列補間も行いません。

name = 'Joe'
greeting = 'Hello, #{name}' # this won't produce "Hello, Joe" 
于 2012-10-31T13:33:25.843 に答える