When a Ruby program needs to embed the value of an expression in a string, string interpolation is the go-to tool:
But sometimes the string can get a little long:
This can be fixed by continuing the string on another line:
But that’s ugly. Much prettier is to use the String#% method:
This takes care of the long line. It also puts each expression on a line by itself, making it easier to read and edit.
String#% is a wrapper for Kernel#sprintf, which has many useful ways to format things. This print statement left-justifies the version string with a width of 9, and right-justifies the use count with a width of 7:
And it does so while looking good.
So the next time you’re interpolating and the string gets too long or hard to read, consider the virtues of String#%.