Ruby Logo

String-interpolation

Learn about string-interpolation in Ruby programming.

Home Ruby String-interpolation

String Interpolation & Manipulation

Master Ruby's powerful string features. Learn interpolation, escape sequences, heredocs, and essential string manipulation methods.

String Interpolation

Interpolation: Use #{} to embed Ruby expressions inside double-quoted strings.

Basic Interpolation Examples

# Basic variable interpolation
name = "Ruby"
age = 30
puts "Hello, #{name}!" # => "Hello, Ruby!"
puts "#{name} is #{age} years old" # => "Ruby is 30 years old"

# Expression interpolation
puts "2 + 3 = #{2 + 3}" # => "2 + 3 = 5"
puts "Today is #{Time.now}" # => "Today is 2024-01-15 10:30:00"

# Method calls in interpolation
text = "hello world"
puts "Uppercase: #{text.upcase}" # => "Uppercase: HELLO WORLD"
puts "Length: #{text.length}" # => "Length: 11"

Escape Sequences

Escape Sequences: Special characters that start with backslash (\) to represent non-printable characters or special meanings.

Common Escape Sequences

# Common escapes
puts "Line 1\nLine 2" # newline
puts "Tab\tSeparated" # tab
puts "Quote: \"Hello\"" # double quote
puts "Backslash: \\" # backslash
puts "Bell: \a" # bell/alert
puts "Return: \r" # carriage return

Unicode Escapes

# Unicode escapes
puts "\u{1F600}" # 😀
puts "\u{1F44D}" # 👍
puts "\u{2764}" # ❤
puts "\u{00A9}" # ©
puts "\u{00AE}" # ®

Heredocs - Multi-line Strings

Heredocs: A way to write multi-line strings that preserve formatting and support interpolation.

Heredoc Examples

# Basic heredoc
message = <<~TEXT
This is a multi-line
string with heredoc.
It preserves formatting!
TEXT

# Heredoc with interpolation
name = "Ruby"
email = <<~EMAIL
Dear #{name},
Welcome to our platform!
Best regards,
The Team
EMAIL

# Different heredoc delimiters
sql = <<~SQL
SELECT * FROM users
WHERE active = true
SQL

Essential String Methods

Case Methods

# Case methods
text = "Hello World"
puts text.upcase # => "HELLO WORLD"
puts text.downcase # => "hello world"
puts text.capitalize # => "Hello world"
puts text.swapcase # => "hELLO wORLD"

Search Methods

# Search methods
text = "Hello World"
puts text.include?("World") # => true
puts text.start_with?("Hello") # => true
puts text.end_with?("World") # => true
puts text.index("World") # => 6

Manipulation Methods

# Manipulation
text = " hello world "
puts text.strip # => "hello world"
puts text.reverse # => " dlrow olleh "
puts text.split # => ["hello", "world"]
puts text.gsub(" ", "-") # => "--hello-world--"

Formatting Methods

# Formatting
text = "hello"
puts text.center(10) # => " hello "
puts text.ljust(10) # => "hello "
puts text.rjust(10) # => " hello"
puts text.ljust(10, "*") # => "hello*****"

String Comparison & Equality

String Comparison Examples

# String comparison
str1 = "hello"
str2 = "hello"
str3 = "Hello"

puts str1 == str2 # => true
puts str1 == str3 # => false
puts str1.eql?(str2) # => true
puts str1.equal?(str2) # => false (different objects)

# Case-insensitive comparison
puts str1.casecmp(str3) # => 0 (equal)
puts str1.casecmp("world") # => -1 (less than)

Best Practices

String Best Practices

  • Use double quotes for interpolation: Single quotes are literal
  • Prefer heredocs for multi-line strings: Better readability
  • Use strip for user input: Remove leading/trailing whitespace
  • Be careful with string mutability: Methods return new strings
  • Use appropriate comparison methods: == vs eql? vs equal?

Common Mistakes to Avoid

  • Forgetting string immutability: Methods don't modify the original
  • Using single quotes for interpolation: Won't work as expected
  • Not handling nil in interpolation: Can cause errors
  • Ignoring encoding issues: Be aware of character encoding
  • Overusing string concatenation: Use interpolation instead

Practice Exercises

1 Basic String Interpolation

Create a greeting message using string interpolation:

# Create variables and use interpolation
name = "Alice"
age = 25
puts "Hello, #{name}! You are #{age} years old."
# => "Hello, Alice! You are 25 years old."

2 Math in Strings

Perform calculations inside string interpolation:

# Do math inside interpolation
price = 19.99
tax_rate = 0.08
puts "Price: $#{price}, Tax: $#{price * tax_rate}, Total: $#{price + (price * tax_rate)}"
# => "Price: $19.99, Tax: $1.5992, Total: $21.5892"

3 Method Calls in Interpolation

Call methods inside string interpolation:

# Call methods inside interpolation
text = "hello world"
puts "Original: #{text}, Uppercase: #{text.upcase}, Length: #{text.length}"
# => "Original: hello world, Uppercase: HELLO WORLD, Length: 11"

4 Complex Interpolation

Create a detailed report using multiple interpolations:

# Create a detailed report
student = "Bob"
score = 85
max_score = 100
percentage = (score.to_f / max_score * 100).round(1)
puts "Student: #{student}\nScore: #{score}/#{max_score} (#{percentage}%)\nGrade: #{score >= 90 ? 'A' : score >= 80 ? 'B' : 'C'}"

Try It Yourself

Practice Makes Perfect! Try these exercises in the code runner below:

  • Create a personal introduction using your name and age
  • Build a shopping receipt with item prices and totals
  • Make a weather report with temperature and conditions
  • Create a student report card with grades and averages

Try It Yourself

Now practice what you've learned! Use the code editor below to try the exercises above and experiment with string interpolation.

Ruby Online Editor
Quick Tips
  • Start with the practice exercises above - try each one!
  • Remember: use #{} for interpolation, not ${}
  • You can do math inside interpolation: puts "Total: #{10 + 5}"
  • Call methods inside interpolation: puts "Name: #{name.upcase}"

What's Next?

Continue Your Ruby Journey

  1. Learn Symbols: Understand Ruby's symbol system and immutability
  2. Explore Regular Expressions: Master pattern matching with strings
  3. Study Collections: Learn about arrays and hashes
  4. Practice String Methods: Build projects using string manipulation
  5. Advanced Topics: Explore encoding, internationalization, and performance

Try It Yourself - Interactive Practice

Learning Tip: The best way to master string interpolation is through hands-on practice! Try these examples and experiment with different variables and expressions!

Interactive Code Runner

Ruby Code Editor
Output will appear here when you run the code...

Quick Navigation

Related Topics

Video Tutorial

Watch and learn string-interpolation

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!