Ruby strings are simply sequences of 8-bit
bytes. They normally hold printable
characters, but that is not a requirement; a string can also hold
binary data. Strings are objects of class
String
.
Strings are often created using string literals---sequences of
characters between delimiters. Because binary data is otherwise
difficult to represent within program source, you can place various
escape sequences in a string literal. Each is replaced with the
corresponding binary value as the program is compiled. The type of
string delimiter determines the degree of substitution performed.
Within single-quoted strings, two consecutive backslashes are replaced
by a single backslash, and a backslash followed by a single quote
becomes a single quote.
'escape using "\\"'
|
� |
escape using "\"
|
'That\'s right'
|
� |
That's right
|
Double-quoted strings support a boatload more escape sequences. The
most common is probably ``\n'', the newline character.
Table 18.2 on page 203 gives the complete list. In addition,
you can substitute the value of any Ruby expression into a string
using the sequence
#{
expr }
.
If the expression is just a global variable, a class variable, or an instance variable,
you can omit the braces.
"Seconds/day: #{24*60*60}"
|
� |
Seconds/day: 86400
|
"#{'Ho! '*3}Merry Christmas"
|
� |
Ho! Ho! Ho! Merry Christmas
|
"This is line #$."
|
� |
This is line 3
|
There are three more ways to construct string literals:
%q
,
%Q
, and ``here documents.''
%q
and
%Q
start delimited single- and double-quoted
strings.
%q/general single-quoted string/
|
� |
general single-quoted string
|
%Q!general double-quoted string!
|
� |
general double-quoted string
|
%Q{Seconds/day: #{24*60*60}}
|
� |
Seconds/day: 86400
|
The character following the ``q'' or ``Q'' is the delimiter. If it is
an opening bracket, brace, parenthesis, or less-than sign, the string
is read until the matching close symbol is found. Otherwise the string
is read until the next occurrence of the same delimiter.
Finally, you can construct a string using a
here document.
aString = <<END_OF_STRING
The body of the string
is the input lines up to
one ending with the same
text that followed the '<<'
END_OF_STRING
|
A here document consists of lines in the source up to, but not
including, the terminating string that you specify after the
<<
characters. Normally, this terminator must start in the first
column. However, if you put a minus sign after the
<<
characters, you can indent the terminator.
print <<-STRING1, <<-STRING2
Concat
STRING1
enate
STRING2
|
produces: