String Interpolation in Ruby
Building strings out of variables and expressions the idiomatic Ruby way, instead of concatenating with +.
2 min read
Gluing strings and variables together with + works in Ruby, but it's rarely how idiomatic Ruby code does it. Interpolation is cleaner, faster, and handles type conversion for you.
The basics
name = "Ada"
age = 36
# Avoid: concatenation
puts "Hello, " + name + "! You are " + age.to_s + " years old."
# Prefer: interpolation
puts "Hello, #{name}! You are #{age} years old."Anything inside #{} is evaluated as a real Ruby expression, and the result is converted to a string automatically — no explicit .to_s needed, and no risk of the classic "can't concatenate a String with an Integer" error that concatenation causes if you forget one.
Interpolation works with any expression
items = ["apple", "banana", "cherry"]
puts "You have #{items.length} items: #{items.join(", ")}"
puts "Total after tax: #{(19.99 * 1.08).round(2)}"
puts "Status: #{age >= 18 ? "adult" : "minor"}"Method calls, arithmetic, even a ternary — all of it can go inside #{}. Keep it readable, though: if the expression gets long or nested, pull it out into a named variable first and interpolate the variable instead.
# Harder to read
puts "Discount: #{items.select { |i| i.start_with?("a") }.length}"
# Clearer
a_items = items.select { |i| i.start_with?("a") }
puts "Discount: #{a_items.length}"Single quotes don't interpolate
name = "Ada"
puts 'Hello, #{name}' # literally prints: Hello, #{name}
puts "Hello, #{name}" # prints: Hello, AdaThis is the single biggest reason to default to double-quoted strings in Ruby: forgetting that single quotes are literal is an easy mistake, and the bug (a raw #{...} showing up in your output) is confusing the first time you see it.
Multi-line strings and heredocs
Interpolation works across multiple lines too, and for longer blocks of text Ruby has heredoc syntax:
name = "Ada"
message = <<~TEXT
Hello, #{name}.
Thanks for signing up. Your account is ready.
TEXT
puts messageThe <<~ (squiggly heredoc) strips leading indentation based on the least-indented line, which is what lets you indent the heredoc body naturally inside your code without that indentation leaking into the actual string.
String formatting as an alternative
For more controlled formatting — padding, fixed decimal places — format (or its alias sprintf) is worth knowing, though interpolation covers most everyday cases:
puts format("Total: $%.2f", 19.9) # Total: $19.90Between #{} interpolation for everyday cases and format for precise layout, you rarely need + concatenation in real Ruby code.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.