Templating with String#%
Yesterday we covered ERB, which is a great general-purpose templating system. However, if all you need is simple string substitution, Ruby's String#% method can be a more concise and efficient option. It allows you to format strings using placeholders, similar to printf-style formatting in C.
name = "Alice"
greeting = "Hello, %s!" % name
# => "Hello, Alice!"
age = 30
info = "Name: %s, Age: %d" % [name, age]
# => "Name: Alice, Age: 30"
pi = 3.14159
formatted_pi = "Pi is approximately %.2f" % pi
# => "Pi is approximately 3.14"
# We can use named placeholders with a hash
template = "Name: %{name}, Age: %{age}, Pi: %<pi>.2f"
named_info = template % { name: "Bob", age: 25, pi: 3.14159 }
# => "Name: Bob, Age: 25, Pi: 3.14"
// In the absence of an actual formatting library, I'm using template
// literals as a comparison, even though it's apples to oranges 🤷♂️
const name = "Alice";
const greeting = `Hello, ${name}!`;
// => "Hello, Alice!"
const age = 30;
const info = `Name: ${name}, Age: ${age}`;
// => "Name: Alice, Age: 30"
const pi = 3.14159;
const formattedPi = `Pi is approximately ${pi.toFixed(2)}`;
// => "Pi is approximately 3.14"
// Poor man's formatting with regex replacement
const template = "Name: %{name}, Age: %{age}, Pi: %{pi}";
const values = { name: "Bob", age: 25, pi: 3.14159.toFixed(2) };
const namedInfo = template
.replace(/%\{(\w+)\}/g, (_, key) => values[key]);
// => "Name: Bob, Age: 25, Pi: 3.14"
Another way of invoking the same functionality is by calling Kernel#format (alias of sprintf), which takes the format string as the first argument, followed by the values to substitute.
All formatting rules can be found in the Ruby documentation.
History
Ruby's printf-style formatting is one of the older parts of the language. sprintf was already present in the Ruby 1.0 series by late 1997, and String#% appears in the Ruby 1.1 sources from January 1998.
Kernel#format came shortly after as a more readable alias for sprintf, and has been part of Ruby since at least Ruby 1.4.0, released in August 1999.
The support for named placeholders, however, came an entire decade later. Both %<name>s and %{name} shipped with Ruby 1.9.1, released in January 2009.