So I'm following this Ruby tutorial: Learn Ruby the Hard Way.
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
Can someone tell me exactly why that is? Do single-quoted strings just ignore escape characters like \n
or \t
?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With