Jump to content

Ruby Programming/Alternate quotes

From Wikibooks, open books for an open world

← Strings | Here documents →


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 %q operator: %q(abc) is the same as 'abc'
  • double quotes with the %Q operator: %Q(abc's) is the same as "abc's"

Alternate single quotes

[edit | edit source]

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

puts 'c:\bus schedules\napolean\the portland bus schedule.txt'

This will result in the following output:

c:\bus schedules\napolean\the portland bus schedule.txt

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

Now let's consider the following string literal:

puts 'c:\napolean\'s bus schedules\tomorrow\'s bus schedule.txt'

This outputs:

c:\napolean's bus schedules\tomorrow's bus schedule.txt

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 %q 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<c:\napolean's documents\tomorrow's bus schedule.txt>

Each line will print out the same text:

c:\napolean's documents\tomorrow's bus schedule.txt

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<c:\napolean's documents\the <bus> schedule.txt>

Alternate double quotes

[edit | edit source]

The %Q operator (notice the case of Q in %Q) 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 %q operator.

 print %Q^Say:\tHello world\n\tHello world\n^
 print %Q(Say:\tHello world\n\tHello world\n)

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

 name = 'Charlie Brown'
 
 puts %Q!Say "Hello," #{name}.!
 puts %Q/What is "4 plus 5"? Answer: #{4+5}/