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

String Formatting

String formatting fills a template with values in a set style, like a form letter with stamped blanks. You can control the decimals and width of what appears.

In this page:

  1. String Formatting
Syntax
ruby
format("%s is %d years old", string_value, integer_value)
"%.2f" % decimal_value

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using %d with a decimal value and expecting rounding, when it truncates.
  2. Passing a single argument to % with several specifiers instead of an array, such as "%s %s" % "a", which raises ArgumentError.
  3. Forgetting %% for a literal percent sign.
🔒

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.