It's time to explore beyond the basics and move into some other areas of Ruby. Here you'll
learn how to use the
sprintf method to format output,
process or generate XML with REXML or XML Builder, use reflection methods, use RubyGems,
create documentation with RDoc, and do some error handling. You'll even do a little
metaprogramming and embedded Ruby (ERB). The purpose of this chapter is to expand your
knowledge and broaden your experience before cutting you loose. After this, only Chapter 11 remains.
Kernel module has a method called
sprintf (which also has a synonym called
format) for creating formatted strings. If you have C
programming in your DNA, as many programmers do, it is likely that you will want to reach
sprintf to do all kinds of string formatting chores
sprintf relies on a format
string—which includes format specifiers, each preceded by a
%—to tell it how to format a string. For example, let's say you
wanted to print out the number 237 in binary format. Enter this:
sprintf( "%b", 237 ) # => "11101101"
The format specifier
%b indicates that you want a
b is the field type
for binary, and the argument
237 is the number you want
to convert to binary, which
sprintf does very handsomely.
sprintf doesn't actually print the return value to
standard output (the screen); to do that you would have to use
printf( "%b", 237 ) # => 11101101
which is nearly identical ...