Ruby has many ways of making strings, which are generally variations of the many ways Perl has of making strings. Double quotes allow values to be interpolated into the string, while single quotes do not. Most escapes are treated literally in single quotes, including the fact that \n
is treated as two characters, a backward slash followed by an n.
Ruby strings may extend any number of lines. This can be useful, but make sure you don’t leave out any closing quotes.
# Double-quoted strings can substitute variables. a = 17 print "a = #{a}\n"; print 'a = #{a}\n'; print "\n"; # If you're verbose, you can create a multi-line string like this. b = <<ENDER This is a longer string, perhaps some instructions or agreement goes here. By the way, a = #{a}. ENDER print "\n[[[" + b + "]]]\n"; print "\nActually, any string can span lines. The line\nbreaks just become part of the string. " print %Q=\nThe highly intuitive "%Q" prefix allows alternative delimiters.\n= print %Q[Bracket symbols match their mates, not themselves.\n]
The <<
notation follows Perl and other languages as a way to multi-line strings. Those don’t generally permit the other varieties to specify multi-line strings, so it’s actually kind of redundant in Ruby.
The %
can be used to create strings using a different delimiter. %Q
x starts a double-quote style string which ends with the next x, rather than the usual double quote character. %q
y starts a single-quote string.