String Class

A String object in Ruby holds and manipulates an arbitrary sequence of one or more bytes, typically representing characters that represent human language. Ruby has a built-in class called String that defines a number of methods that are used frequently when programming Ruby. Those methods are listed at the end of this section. Following are string-related features Ruby.

Expression Substitution

Expression substitution is a means of embedding the value of any Ruby expression into a string using #{ and }:

x, y, z = 12, 36, 72

puts "The value of x is #{ x }.

puts "The sum of x and y is #{ x + y }.

puts "The average was #{ (x + y + z)/3 }."

General Delimited Strings

With general delimited strings, you can create strings inside a pair of matching though arbitrary delimiter characters, e.g., !, (, {, <, etc., preceded by a percent character (%). Q, q, and x have special meanings. General delimited strings can be nested:

%{Ruby is fun.} # => "Ruby is fun."

%Q{ Ruby is fun. } # => " Ruby is fun. "

%q[Ruby is fun.] # equivalent to a single-quoted string

%x!ls! # => equivalent to back tick command output 'ls'

Here Documents

Here documents allow you to quickly build multiline strings inside a nested pair of characters or words, preceded by <<. ", ', ', and - have special meanings. Here’s an example:

# double-quoted string
puts <<x
To every thing there is a season,
and a time to every purpose
under the heaven.
x

# double-quoted string, assigned to variable
hamlet = <<"yorick" Alas, poor ...

Get Ruby Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.