1. Computing

String Literals

By

Multi-Line Strings

Most languages don't allow multi-line string literals, but Ruby does. There's no need to end your strings and append more strings for the next line, Ruby handles multi-line string literals just fine with the default syntax.


puts "This is a string
that spans multiple lines.
In most languages, this would
not work, but not in Ruby."

Alternate Syntax

As with most other literals, Ruby provides an alternate syntax for string literals. If you're using a lot of quote characters inside your literals, for example, you may want to use this syntax. When you use this syntax is a matter of style, they're usually not needed for strings.

To use the alternate syntax, use the following sequence for single-quoted strings %q{ … }. Similarly, use the following syntax for double-quoted strings %Q{ … }. This alternate syntax follows all the same rules as their "normal" cousins. Also note that you can use any characters you with instead of braces. If you use a brace, square bracket, angle bracket or parenthesis, then the matching character will end the literal. If you don't want to use matching characters, you can use any other symbol (anything not a letter or number). The literal will be closed with another of the same symbol. The following example shows you several ways to use this syntax.


puts %Q{Expected form}
puts %Q[Slightly different]
puts %Q(Again, slightly different)
puts %Q!Something important, maybe?!
puts %Q#Hmmm?#

The alternate syntax also works as a multi-line string.


puts %Q{This is a
multi-line string.
It works just like
normal single or
double quoted multi-
line strings.}
  1. About.com
  2. Computing
  3. Ruby
  4. Beginning Ruby
  5. Strings
  6. String Literals

©2014 About.com. All rights reserved.