Output With Variables
Part of the Fundamentals section of Coddy's Ruby journey — lesson 28 of 88.
Now that you know how to output text, let's combine output methods with variables. Ruby makes it easy to include variable values in your output using string interpolation.
String interpolation lets you embed variables directly inside a string using #{}:
name = "Alice"
age = 25
puts "My name is #{name}"
puts "I am #{age} years old"This outputs:
My name is Alice
I am 25 years oldThe #{} syntax tells Ruby to evaluate whatever is inside the braces and insert the result into the string. You can even include expressions:
price = 10
quantity = 3
puts "Total: #{price * quantity}"This outputs:
Total: 30Important: String interpolation only works with double quotes. Single quotes treat everything literally:
name = "Ruby"
puts "Hello, #{name}" # Hello, Ruby
puts 'Hello, #{name}' # Hello, #{name}Challenge
EasyYou are provided with the following variables:
product = "Laptop"
price = 999
quantity = 3Use string interpolation with puts to display the following three lines of output:
- Print
Product: Laptop(using theproductvariable) - Print
Price: $999(using thepricevariable) - Print
Total: $2997(calculateprice * quantityinside the interpolation)
Each line should be printed using a separate puts statement with string interpolation. Remember to use double quotes for interpolation to work.
Cheat sheet
String interpolation lets you embed variables directly inside a string using #{}:
name = "Alice"
age = 25
puts "My name is #{name}"
puts "I am #{age} years old"You can include expressions inside the braces:
price = 10
quantity = 3
puts "Total: #{price * quantity}"Important: String interpolation only works with double quotes, not single quotes:
name = "Ruby"
puts "Hello, #{name}" # Hello, Ruby
puts 'Hello, #{name}' # Hello, #{name}Try it yourself
# Variables are already defined for you
product = "Laptop"
price = 999
quantity = 3
# TODO: Write your code below
# Use string interpolation with puts to display:
# 1. Product: Laptop
# 2. Price: $999
# 3. Total: $2997 (calculate price * quantity inside the interpolation)This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False