← Back to Ruby Course | Chapter 1: Setup & Basics | Lesson 7 of 7

String Interpolation

String interpolation lets you drop a value right inside a sentence, like filling in a blank in a story. Ruby swaps the marker for the actual value.

In this page:

  1. String Interpolation
Syntax
ruby
name = "value"
puts "text #{name} more text"
puts "sum: #{expression}"

String Interpolation

Ruby lets you embed expressions directly inside a double-quoted string with #{expression}, which evaluates the expression and inserts its string form.

This only works in double-quoted strings, not single-quoted ones. Interpolation is the idiomatic Ruby way to build strings, generally preferred over concatenation with +.

Warning: String interpolation only works inside double quotes -- 'Hello #{name}' with single quotes prints the literal text, not the interpolated value.

Example: String Interpolation

markup
name = "Ruby"
version = 3.2

puts "Hello, #{name}! Version: #{version}"
puts "2 + 2 = #{2 + 2}"
puts 'No interpolation here: #{name}'
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using single quotes as in 'Hello, #{name}', which prints #{name} literally.
  2. Forgetting the braces, such as "Hello #name", which prints #name.
  3. Concatenating a number with + such as "Total: " + 5, which raises TypeError; interpolate with #{5}.
Chapter Summary
  • Ruby is a language you can run with IRB or as scripts after installing it.
  • puts, print, and p display output, and comments document code.
  • String interpolation inserts values into text.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.