Menu
Coddy logo textTech

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 old

The #{} 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: 30

Important: 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 icon

Challenge

Easy

You are provided with the following variables:

product = "Laptop"
price = 999
quantity = 3

Use string interpolation with puts to display the following three lines of output:

  1. Print Product: Laptop (using the product variable)
  2. Print Price: $999 (using the price variable)
  3. Print Total: $2997 (calculate price * quantity inside 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals