Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - what's the difference between single and double quotes? [duplicate]

Tags:

ruby

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?

like image 372
Nekkoru Avatar asked Oct 31 '12 13:10

Nekkoru


1 Answers

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" 
like image 73
Sergio Tulentsev Avatar answered Nov 07 '22 17:11

Sergio Tulentsev