0
0
RubyHow-ToBeginner · 3 min read

How to Format String in Ruby: Syntax and Examples

In Ruby, you can format strings using string interpolation with #{}, or by using sprintf and format methods with format specifiers like %s and %d. These methods let you insert variables and control the output style inside strings easily.
📐

Syntax

Ruby offers several ways to format strings:

  • String Interpolation: Insert variables directly inside a string using #{variable}.
  • sprintf / format: Use format specifiers like %s for strings, %d for integers, and %f for floats inside a format string.
ruby
name = "Alice"
age = 30
height = 1.75

# String interpolation
puts "Name: #{name}, Age: #{age}, Height: #{height}m"

# sprintf or format method
formatted = sprintf("Name: %s, Age: %d, Height: %.2f m", name, age, height)
puts formatted
Output
Name: Alice, Age: 30, Height: 1.75m Name: Alice, Age: 30, Height: 1.75 m
💻

Example

This example shows how to use string interpolation and sprintf to format a message with variables and control decimal places for floats.

ruby
product = "Book"
price = 12.5
quantity = 4

# Using interpolation
message1 = "You bought #{quantity} #{product}s for $#{price * quantity} total."
puts message1

# Using format with specifiers
message2 = format("You bought %d %ss for $%.2f total.", quantity, product, price * quantity)
puts message2
Output
You bought 4 Books for $50.0 total. You bought 4 Books for $50.00 total.
⚠️

Common Pitfalls

Common mistakes when formatting strings in Ruby include:

  • Forgetting to use double quotes "" for interpolation (single quotes '' do not interpolate).
  • Using wrong format specifiers that don't match variable types (e.g., %d for a string).
  • Not controlling float precision, which can lead to long decimal outputs.
ruby
name = 'Bob'

# Wrong: single quotes prevent interpolation
puts 'Hello, #{name}'  # prints literally

# Right: double quotes allow interpolation
puts "Hello, #{name}"

# Wrong: using %d for string
# puts sprintf("Name: %d", name)  # raises error

# Right: use %s for string
puts sprintf("Name: %s", name)
Output
Hello, #{name} Hello, Bob Name: Bob
📊

Quick Reference

MethodUsageExample
String InterpolationInsert variables inside double quotes using #{variable}"Hello, #{name}"
sprintf / formatUse format specifiers like %s, %d, %fsprintf("Age: %d", age)
%.nfControl float decimal places (n digits)"%.2f" % 3.14159
%sFormat string"%s" % "text"
%dFormat integer"%d" % 42

Key Takeaways

Use double quotes and #{variable} for simple and readable string formatting.
Use sprintf or format with % specifiers for precise control over output format.
Match format specifiers to variable types to avoid errors.
Control float precision with %.nf to limit decimal places.
Single quotes do not support interpolation in Ruby.