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:
Syntax
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
name = "Alice"
score = 92.567
puts format("Name: %s, Score: %.2f", name, score)
puts "Padded: %05d" % 42
Login to try C/C++/Java/PHP code in the editor
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
- Using
%dwith a decimal value and expecting rounding, when it truncates. - Passing a single argument to
%with several specifiers instead of an array, such as"%s %s" % "a", which raisesArgumentError. - Forgetting
%%for a literal percent sign.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: