liveBook · Manning

Interpolation

As explained in The Well-Grounded Rubyist, Fourth Edition

String interpolation is the Ruby language feature that evaluates embedded expressions and inserts their results into a string or regular expression.

Ruby interpolation puts the value of an expression inside a string. In a double-quoted string, write the expression between `#{` and `}`: `"Two plus two is #{2 + 2}."` produces `"Two plus two is 4."`. Ruby evaluates what is inside the braces and inserts the result, rather than displaying the braces. section 2.2.3 section 8.1.1

puts "This ticket is for: #{ticket.event}, at #{ticket.venue}.\n" +
"The performer is #{ticket.performer}.\n" +
"The seat is #{ticket.seat}, " +
"and it costs $#{"%.2f." % ticket.price}"

A ticket-printing example inserts method results where they belong in the output. Interpolation makes the intended layout easier to see and replaces several separate printing calls; `+` joins the remaining string pieces. section 2.2.3

Quotation determines whether interpolation happens. `"#{2 + 2}"` evaluates the expression, but `'#{2 + 2}'` keeps those characters literal. To keep them literal inside double quotes, escape the opening `#` with a backslash. The same single- versus double-quoted distinction applies to the corresponding heredoc forms; `%Q{}` and `%{}` produce double-quoted-style strings. section 8.1.1

When inserted text becomes a regexp pattern

Interpolation also works in a regexp: with `str = "def"`, `/abc#{str}/` becomes `/abcdef/`. Be careful when the inserted string contains regexp syntax. If `str = "a.c"`, `/#{str}/` matches both `"a.c"` and `"abc"`, because the inserted dot acts as a regexp wildcard. Use `/#{Regexp.escape(str)}/` when the string should be matched literally; it matches `"a.c"` but not `"abc"`. section 11.6.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains expression evaluation, quoting controls, and regexp escaping through worked examples, without descending into implementation internals.
Examples
Uses ticket output, arithmetic in differently quoted strings, and a dot-containing regexp that matches too broadly.
What it assumes
Builds on variables and method calls while introducing the `#{...}` mechanism directly; regexp examples assume familiarity with pattern matching.
What you can do after
Apply it to format Ruby strings and interpolate literal text safely into regexps with Regexp.escape.
How it connects
Connects string literals, concatenation, method return values, regular expressions, and Regexp.escape.

Also explained in

Compare how 4 books explain interpolation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.