String Interpolation
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 2 of 56.
Ruby lets you embed variables and expressions directly inside a double-quoted string with #{...}. This is called string interpolation.
name = "Sam"
age = 30
puts "#{name} is #{age} years old." # Sam is 30 years old.The expression inside #{...} can be anything Ruby evaluates:
price = 19.5
puts "Total: $#{price * 1.2}" # Total: $23.4Interpolation only works in double-quoted strings. Single quotes treat #{...} as plain text.
x = 5
puts "x is #{x}" # x is 5
puts 'x is #{x}' # x is #{x}Challenge
BeginnerRead a name and an age (two lines of input). Print one line in the format:
Hello, <name>! In 5 years you will be <age+5>.For input Alice then 30, the output is:
Hello, Alice! In 5 years you will be 35.Cheat sheet
String interpolation embeds variables/expressions in double-quoted strings using #{...}:
name = "Sam"
age = 30
puts "#{name} is #{age} years old." # Sam is 30 years old.
puts "Total: $#{19.5 * 1.2}" # Total: $23.4Single quotes treat #{...} as plain text — interpolation only works with double quotes.
Try it yourself
name = gets.chomp
age = gets.to_i
# TODO: use string interpolation to print the message
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier