0
0
Rubyprogramming~5 mins

String interpolation with #{} in Ruby

Choose your learning style9 modes available
Introduction

String interpolation lets you put values or expressions inside a string easily.

When you want to include a variable's value inside a message.
When you want to combine text and numbers in one string.
When you want to show the result of a calculation inside a string.
When you want to build a sentence that changes based on data.
Syntax
Ruby
"Hello, #{variable_or_expression}!"
Use double quotes "" for strings with interpolation.
Inside #{}, you can put variables or any Ruby expression.
Examples
Insert the value of name inside the string.
Ruby
name = "Alice"
puts "Hello, #{name}!"
Show a number variable inside a sentence.
Ruby
age = 10
puts "You are #{age} years old."
Calculate inside the string and show the result.
Ruby
puts "5 + 3 = #{5 + 3}"
Sample Program

This program shows how to put variables inside a string using #{ }.

Ruby
name = "Bob"
age = 25
puts "My name is #{name} and I am #{age} years old."
OutputSuccess
Important Notes

Interpolation only works inside double-quoted strings, not single-quoted.

You can put any Ruby code inside #{}, like method calls or math.

Summary

Use #{ } inside double quotes to insert values or expressions into strings.

This makes building dynamic messages easy and readable.