How does string interpolation work in Ruby?

Short answer

Use "Hello #{name}" — double quotes only. Any Ruby expression works inside the braces, and to_s is called automatically.

ruby
name = "Dom"
count = 15

"#{name} has #{count} videos"
"Average: #{count / 5.0}"
"#{name.upcase}!"
'#{name}'                     # single quotes do NOT interpolate

#Formatting numbers

ruby
format("%.2f", 3.14159)              # "3.14"
format("%05d", 42)                   # "00042"
format("%-10s|", "left")             # "left      |"
format("%d:%02d", 10, 7)             # "10:07"
"%.1f%%" % 45.67                     # "45.7%"

format (also spelled sprintf) uses C-style specifiers. It is what you want for aligned columns — interpolation cannot pad.

#Heredocs for multi-line text

ruby
message = <<~TEXT
  Hi #{name},

  You have #{count} lessons remaining.
TEXT

The squiggly <<~ strips the common leading indentation, so the heredoc can be indented with the surrounding code. Use <<~'TEXT' to disable interpolation.

#Concatenation alternatives

ruby
"a" + "b"          # requires both to be strings
"a" << "b"         # appends in place — mutates the receiver
["a", "b"].join    # best for many pieces

<< mutating in place is a real gotcha: if that string is shared, you have just changed it everywhere.

#Frozen string literals

ruby
# frozen_string_literal: true

This magic comment at the top of a file makes all string literals immutable, which saves allocations and catches accidental mutation. It is standard in modern Ruby codebases.