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 (for some reason the community style guide doesn’t seem to agree on this, but I think that’s ok).
Here is an example:
time = 5 message = "Processing of the data has finished in %d seconds" % [time] puts message
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 formatted. 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:
score = 78.5431 puts "The average is %0.2f" % [score]
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:
puts "122 in HEX is %x" % [122]
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
puts "The number is %04d" % [20]
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:
Alternatively, you can use the .ljust and .rjust
methods from the String class to do the same.
Example:
names_with_ages = [["john", 20], ["peter", 30], ["david", 40], ["angel", 24]] names_with_ages.each { |name, age| puts name.ljust(10) + age.to_s } # Prints the following table john 20 david 30 peter 40 angel 24
Conclusion
As you have seen ruby & rails string formatting is really easy, it all comes down to understanding the different format specifiers available to you.
I hope you enjoyed this fast trip into the world of output formatting! Don’t forget to subscribe to my newsletter so I can send you more great content 🙂
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]
You code looks ok, but since 20 is already 2 digits long you won’t get any padding. Try with
"%04d" % number
.