Section 2.3. Using Here-Documents


2.2. Representing Strings with Alternate Notations

Sometimes we want to represent strings that are rich in metacharacters such as single quotes, double quotes, and more. For these situations, we have the %q and %Q notations. Following either of these is a string within a pair of delimiters; I personally favor square brackets ([]).

The difference between the %q and %Q variants is that the former acts like a single-quoted string, and the latter like a double-quoted string.

S1 = %q[As Magritte said, "Ceci n'est pas une pipe."] s2 = %q[This is not a tab: (\t)]  # same as: 'This is not a tab: \t' s3 = %Q[This IS a tab: (\t)]      # same as: "This IS a tab: \t"


Both kinds of notation can be used with different delimiters. Besides brackets, there are other paired delimiters (parentheses, braces, angle brackets):

s1 = %q(Bill said, "Bob said, 'This is a string.'") s2 = %q{Another string.} s3 = %q<Special characters '"[](){} in this string.>


There are also "nonpaired" delimiters. Basically any character may be used that is not alphanumeric, not whitespace, printable, and not a paired character.

s1 = %q:"I think Mrs. O'Leary's cow did it," he said.: s2 = %q*\r is a control-M and \n is a control-J.*





The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net