Strings

A string is an array of bytes (octets) and an instance of class String:

"abc"

Double-quoted strings allow substitution and backslash notation.

'abc'

Single-quoted strings don’t allow substitution and allow backslash notation only for \\ and \'.

String concatenation

Adjacent strings are concatenated at the same time Ruby parses the program.

"foo" "bar"           # means "foobar"

Expression substitution

#$var and #@var are abbreviated forms of #{$var} and #{@var}. Embeds value of expression in #{...} into a string.

Backslash notation

In double-quoted strings, regular expression literals, and command output, backslash notation can be represent unprintable characters, as shown in Table 2-1.

Table 2-1. Backslash notations

Sequence

Character represented

\n

Newline (0x0a)

\r

Carriage return (0x0d)

\f

Formfeed (0x0c)

\b

Backspace (0x08)

\a

Bell (0x07)

\e

Escape (0x1b)

\s

Space (0x20)

\nnn

Octal notation (n being 0-7)

\xnn

Hexadecimal notation (n being 0-9, a-f, or A-F)

\cx, \C-x

Control-x

\M-x

Meta-x (c | 0x80)

\M-\C-x

Meta-Control-x

\x

Character x

`command`

Converts command output to a string. Allows substitution and backslash notation

General delimited strings

The delimiter ! in expressions like this: %q!...! can be an arbitrary character. If the delimiter is any of the following: ( [ { <, the end delimiter becomes the corresponding closing delimiter, allowing for nested delimiter pairs.

%!foo!
%Q!foo!

Equivalent to double quoted string "foo"

%q!foo!

Equivalent to single ...

Get Ruby in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.