Chapter 10. More Fun with Ruby

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.

Formatting Output with sprintf

The 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 for sprintf to do all kinds of string formatting chores for you. 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 binary result. 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, another Kernel method:

printf( "%b", 237 ) # => 11101101

which is nearly identical ...

Get Learning Ruby 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.