Strings in Ruby - General Delimited Strings
(Page 2 of 4 )
Another way to create strings is with general delimited strings, which are all preceded by a % and then followed by a matched pair of delimiter characters, such as!,{, or[(must be nonalphanumeric). The string is embedded between the delimiters. All of the following examples are delimited by different characters (you can even use quote characters):
comedy = %!As You Like It!
history = %[Henry V]
tragedy = %(Julius Ceasar)
You can also use%Q, which is the equivalent of a double-quoted string;%q, which is equivalent to a single-quoted string; or%xfor a back-quoted string (`) for command output.
Here Documents
A here document allows you to build strings from multiple lines on the fly, while preserving newlines. A here document is formed with a<< and a delimiting character or string of your choice. I’ll save Shakespeare’s 29th sonnet as a here document, with29as the delimiter:
sonnet = <29
When in disgrace with fortune and men's eyes
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself, and curse my fate,
Wishing me like to one more rich in hope,
Featured like him, like him with friends possessed,
Desiring this man's art, and that man's scope,
With what I most enjoy contented least;
Yet in these thoughts my self almost despising,
Haply I think on thee, and then my state,
Like to the lark at break of day arising
From sullen earth, sings hymns at heaven's gate;
For thy sweet love remembered such wealth brings
That then I scorn to change my state with kings.
29
This document is stored in the string sonnet, but you can create a here document without placing it in a string. Wherever the line breaks, a record separator (such as\n) is inserted at that place. Now use:
puts sonnet
You’ll see for yourself how the lines break.
You can also “delimit the delimiter” for various effects:
sonnet = <<hamlet # same as double-quoted string
O my prophetic soul! My uncle!
hamlet
sonnet = <<"hamlet" # again as double-quoted string
O my prophetic soul! My uncle!
hamlet
sonnet = <<'ghost' # same as single-quoted string
Pity me not, but lend thy serious hearing
To what I shall unfold.
ghost
my_dir = <<`dir` # same as back ticks
ls -l
dir
ind = <<-hello # for indentation
Hello, Matz!
hello
Next: Concatenating Strings >>
More Ruby-on-Rails Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of Learning Ruby, written by Michael Fitzgerald (O'Reilly, 2007; ISBN: 0596529864). Check it out today at your favorite bookstore. Buy this book now.
|
|