Ruby string interpolation
This course covers how Ruby builds strings with interpolation. It compares #{} with + and << concatenation, including TypeError, FrozenError and aliasing. It shows method calls, arithmetic and nested strings inside the braces, with a plural pattern that relies on nil.to_s returning an empty string. It explains how heredocs interpolate, how to escape or disable it, and how format, sprintf and % control decimals and padding. It ends with Rails I18n placeholders written as %{} in YAML translation files.
What you'll learn
- ✓Why interpolation calls .to_s and avoids the TypeError of + concatenation
- ✓How << mutates strings in place and causes aliasing bugs
- ✓Running method calls, arithmetic and nested strings inside #{}
- ✓Escaping and disabling interpolation in heredocs
- ✓Formatting decimals and padding with format, sprintf and %
- ✓Using %{} placeholders with Rails I18n.t in translation files
Interpolation vs. concatenation
Run that last line and Ruby raises TypeError: no implicit conversion of Integer into String. + on strings needs both sides to be strings already, and age is an Integer. You'd have to write age.to_s by hand to make the line work. Interpolation avoids the problem:
Read the full lesson free →Curriculum
7 lessonsInterpolation vs. concatenation
Compares #{} with + and << concatenation, covering .to_s conversion, single quotes and shared mutable strings.
Calling methods inside interpolation
Shows that #{} evaluates full expressions and when logic should move into a named variable first.
Nested interpolation
Explains inside-out resolution of nested interpolation and a plural pattern that depends on nil.to_s being empty.
Interpolation inside heredocs
Covers heredoc interpolation, escaping with a backslash, the <<~ and <<- forms, and single-quoted markers.
format, sprintf, and %
Uses format, sprintf and String#% to fix decimal places and pad numbers and strings in receipt lines.
Rails' interpolation: I18n and %{}
Explains why Rails translation files use %{} placeholders filled by I18n.t instead of Ruby's #{}.
Putting interpolation together
Reviews every tool through the receipt_line example and a summary table separating #{} from %{}.