Ruby Format String Examples

Use the format string syntax. See examples for formatting values in many ways.

Format. A string can be created with concatenation. This sometimes requires many statements. It can be complex. With a format string we build more complex strings.

A syntax form. In Ruby we apply the string format syntax (the "%" operator) to ease this creation of formatted string data. After the "%" we specify arguments.

A first example. We use the percentage sign ("%") to specify a format code within a string. And we also apply the "%" sign after the string, to indicate the arguments.
One argument: In the first format example, we use one argument. We insert the 12 as a decimal number into the "%d" code.
Two arguments: We next use two arguments. We use a "%d" and the "%s" string code. We specify the two values in an array.
Ruby program that formats string # Use digit format. format = "Number is %d" % 12 puts format # Use two formatting codes. format = "Number is %d, type is %s" % [13, "cat"] puts format Output Number is 12 Number is 13, type is cat

Padding. A format string can pad strings. We specify the total width of the desired string. And an amount of padding (space characters) is added on the left or right side to fit the size.
Positive: With a positive padding, the string is aligned to the right. To have a 10 char string, use the code "%10s."
Negative: A negative padding adds whitespace to the right. Try the code "%-10s" to pad to ten characters.
Ruby program that pads string # Align string to the right (pad the left). right = "[%10s]" % "carrot" puts right # Align to the left. left = "[%-10s]" % "carrot" puts left Output [ carrot] [carrot ]

Floating-point. Often when representing floating-point numbers as strings, we want to control the number of digits past the decimal.
And: With format syntax, we can use a "precision" like ".2" after the percentage mark and before an "f."
Tip: The precision, like 2, indicates the number of post-decimal digits—so we get "12.35."
Rounding: This operation rounds numbers, so 12.345 is rounded to 12.34. We can specify greater precisions.
Ruby program that formats floating-point numbers # Use two digits after the decimal place for floating-point. result = "Result is %.2f" % 12.3456 p result # Use three digits. result = "Result is %.3f" % 12.3456 p result Output "Result is 12.35" "Result is 12.346"

String interpolation. This is another kind of format syntax. When we use the "#" and curly-brackets in a string literal, we can capture variables and format them as strings.
Tip: For this syntax form, we must use the "#{identifier}" pattern. Ruby then inserts a value.
Ruby program that uses string interpolation name = "Plato" id = 65 # Use string interpolation to format variables. # ... The names specified in brackets must match exactly. result = "Name is #{name}, ID is #{id}" p result Output "Name is Plato, ID is 65"

Format syntax, names. We can specify a mapping from string format identifiers to actual program variables. Here we specify "b" means the breed variable and "z" means size.
Tip: This syntax makes it possible to map variables to a string format pattern.
And: Suppose were name variables in a program. The string does not need changing, just the mapping.
Ruby program that uses format syntax with names breed = "Spaniel" size = 65 # Use names in format syntax. # ... We use "b" as the name for breed and "z" for size. result = "Breed %{b} size %{z}" % {b: breed, z: size} p result Output "Breed Spaniel size 65"

Kernel::sprintf. The string format syntax, which uses the "%" symbol, calls into the Kernel::sprintf method. We can use sprintf or format() explicitly, but there is no benefit to this.
Ruby program that uses Kernel, sprintf, format # String format syntax. result = "There are %d units." % 10 puts result # Call sprintf for equivalent functionality. result = Kernel::sprintf("There are %d units.", 10) puts result # Call format. result = Kernel::format("There are %d units.", 10) puts result Output There are 10 units. There are 10 units. There are 10 units.

Interpolation benchmark. Is string interpolation fast? I compared this syntax to a concatenation of 4 values. I found interpolation was faster.
Version 1: This version of the code uses string interpolation syntax to combine 4 values together.
Version 2: This code uses string concatenation with the plus operator to merge 4 values into 1 string. This version was slower.
Result: String interpolation is a clear performance winner in these simple tests. I recommend it for most Ruby programs.
Further: I tested string format syntax, with "%s" and "%d" and found it to be even slower than concat.
Ruby program that times string interpolation, concat n1 = Time.now.usec # Version 1: use string interpolation syntax. 90000.times do cat = "Felix" size = 100 result = "Name: #{cat}, size: #{size}" end n2 = Time.now.usec # Version 2: use string concatenation. 90000.times do cat = "Felix" size = 100 result = "Name: " + cat + ", size: " + String(size) end n3 = Time.now.usec # Total milliseconds. puts ((n2 - n1) / 1000) puts ((n3 - n2) / 1000) Output 44 ms: String interpolation syntax 71 ms: String concat (plus)

A perspective. Most requirements in programming are not glamorous. They involve no inventive algorithms. Instead, we often format strings.

We process text. In Ruby the string format syntax helps make this mundane stuff easier. A method (sprintf) can be used instead of the "%" symbol.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.