Ruby Programming/Alternate quotes

In Ruby, there's more than one way to quote a string literal. Much of this will look familiar to Perl programmers.

These alternative methods are:
 * single quotes with the  operator:   is the same as
 * double quotes with the  operator:   is the same as

Alternate single quotes
Let's say we are using single quotes to print out the following path.

This will result in the following output:

The single quotes keep the,  , and   from being treated as escape sequences (the same cannot be said for wikibooks' syntax highlighting).

Now let's consider the following string literal:

This outputs:

Escaping the apostrophes makes the code less readable and makes it less obvious what will print out.

Luckily, in Ruby, there's a better way. You can use the  operator to apply single-quoting rules, and choose your own delimiter. This delimiter will mark the beginning and end of the string literal.

puts %q!c:\napolean's documents\tomorrow's bus schedule.txt! puts %q/c:\napolean's documents\tomorrow's bus schedule.txt/ puts %q^c:\napolean's documents\tomorrow's bus schedule.txt^ puts %q(c:\napolean's documents\tomorrow's bus schedule.txt) puts %q{c:\napolean's documents\tomorrow's bus schedule.txt} puts %q

Each line will print out the same text:

You can use any punctuation you want as a delimiter, not just the ones listed in the example.

Of course, if your chosen delimiter appears inside of the string literal, then you need to escape it.

puts %q#c:\napolean's documents\tomorrow's \#9 bus schedule.txt#

If you use matching braces to delimit the text, however, you can nest braces, without escaping them.

puts %q(c:\napolean's documents\the (bus) schedule.txt) puts %q{c:\napolean's documents\the {bus} schedule.txt} puts %q

Alternate double quotes
The  operator (notice the case of Q in  ) allows you to create a string literal using double-quoting rules, but without using the double quote as a delimiter. It works much the same as the  operator.

Just like double quotes, you can interpolate Ruby code inside of these string literals.