Formatted Output

Ruby provides a highly flexible way of formatting information for output, called printf. It is borrowed from the C language, and for the convenience of C programmers (including, presumably, the author of Ruby), the formatting specifications are like those used in C's standard I/O library. So if you already program in C and are familiar with how printf works, you can skip most of this section; the main differences that you need to know are that printf is a method of IO objects (including files) whereas sprintf is not (it returns a string).

Let's start with printf. You can use it just as you use print, except you give it a format string as an extra first argument. Certain sequences of characters in the format string will be subsituted ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.