Junior Track Roadmap

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
Free preview · Lesson 1 4 min read

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 lessons
Type to start searching...