← Back to Ruby Course | Chapter 3: Strings | Lesson 4 of 7

String Formatting

In this page:

  1. String Formatting

String Formatting

The % operator (or the format/sprintf methods) formats values into a string using format specifiers like %s, %d, and %.2f, similar to C's printf. This gives more precise control over output than plain interpolation, such as fixed decimal places or zero-padding. format and sprintf are aliases for the same underlying behavior.

Note: format("%.2f", value) is the standard way to format a number to exactly 2 decimal places.

Example: String Formatting

markup
name = "Alice"
score = 92.567

puts format("Name: %s, Score: %.2f", name, score)
puts "Padded: %05d" % 42
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.