Black Bytes
Share this post!

Ruby String Formatting

Let’s talk about how you can format strings in ruby.

Why would you want to format a string? Well, you may want to do things like have a leading zero even if the number is under 10 (example: 01, 02, 03…), or have some console output nicely formatted in columns.

In other languages you can use the printf function to format strings, and if you have ever used C you are probably familiar with that. To use printf you have to define a list of format specifiers and a list of variables or values.

Getting Started with Ruby String Formatting

While sprintf is also available in ruby, in this post we will use a more idiomatic way (the community style guide doesn’t seem to agree thought).

Here is an example:

Output => "Processing of the data has finished in 5 seconds"

In this example, %d is the format specifier (here is a list of available specifiers) and time is the variable we want formated. A %d format will give us whole numbers only.

If we want to display floating point numbers we need to use %f. We can specify the number of decimal places we want like this: %0.2f.

The 2 here indicates that we want to keep only two decimal places.

Here is an example:

Output => The average is 78.54

Remember that the number will be rounded up. For example, if I used 78.549 in the last example, it would have printed 78.55.

Converting and Padding

You can convert a decimal number and print it as hexadecimal. Using the %x format:

Output => 122 in HEX is 7a

To pad a string:

Use this format for padding a number with as many 0’s as you want: %0<number of zeros>d

Output => The number is 0020

You can also use this ruby string format trick to create aligned columns of text. Replace the 0 with a dash to get this effect:

ruby string format

Alternatively, you can use the .ljust and .rjust methods from the String class to do the same.

Example:

Conclusion

As you have seen ruby & rails string formatting is really easy, it all comes down to understanding the different format specificiers available to you.

I hope you enjoyed this fast trip into the world of output formatting! If you did don’t forget to subscribe to my newsletter using the form below so I can send you more great content 🙂

2 comments
Jordan Christley says 9 months ago

I am trying to use the 0 padding method in a practice on Cloud9, and although the server is recognizing and accepting it as valid ruby code, I am not getting the desired output. Here is my code:

number = 20
puts "%02d" % [number]

    Jesus Castello says 9 months ago

    You code looks ok, but since 20 is already 2 digits long you won’t get any padding. Try with "%04d" % number.

Comments are closed