Section 2.2. Representing Strings with Alternate Notations

2.1. Representing Ordinary Strings

A string in Ruby is simply a sequence of 8-bit bytes. It is not null-terminated as in C, so it can contain null characters. It may contain bytes above 0xFF, but such strings are meaningful only if some certain character set (encoding) is assumed. (For more information on encodings, refer to Chapter 4.

The simplest string in Ruby is single-quoted. Such a string is taken absolutely literally; the only escape sequences recognized are the single quote (\') and the escaped backslash itself (\\):

s1 = 'This is a string'    # This is a string s2 = 'Mrs. O\'Leary'       # Mrs. O'Leary s3 = 'Look in C:\\TEMP'    # Look in C:\TEMP

A double-quoted string is more versatile. It allows many more escape sequences, such as backspace, tab, carriage return, and linefeed. It also allows control characters to be embedded as octal numbers:

s1 = "This is a tab: (\t)" s2 = "Some backspaces: xyz\b\b\b" s3 = "This is also a tab: \011" s4 = "And these are both bells: \a \007"

Double-quoted strings also allow expressions to be embedded inside them. See section 2.21, "Embedding Expressions Within Strings."

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

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: