Section 2.10. Using Strings As IO Objects


2.9. Formatting a String

This is done in Ruby as it is in C, with the sprintf method. It takes a string and a list of expressions as parameters and returns a string. The format string contains essentially the same set of specifiers available with C's sprintf (or printf).

name = "Bob" age = 28 str = sprintf("Hi, %s... I see you're %d years old.", name, age)


You might ask why we would use this instead of simply interpolating values into a string using the #{expr} notation. The answer is that sprintf makes it possible to do extra formatting such as specifying a maximum width, specifying a maximum number of decimal places, adding or suppressing leading zeroes, left-justifying, right-justifying, and more.

str = sprintf("%-20s  %3d", name, age)


The String class has a method % that does much the same thing. It takes a single value or an array of values of any type:

str = "%-20s  %3d" % [name, age]  # Same as previous example


We also have the methods ljust, rjust, and center; these take a length for the destination string and pad with spaces as needed:

str = "Moby-Dick" s1 = str.ljust(13)           # "Moby-Dick" s2 = str.center(13)          # "  Moby-Dick  " s3 = str.rjust(13)           # "    Moby-Dick"


If a second parameter is specified, it is used as the pad string (which may possibly be truncated as needed):

str = "Captain Ahab" s1 = str.ljust(20,"+")       # "Captain Ahab++++++++" s2 = str.center(20,"-")      # "Captain Ahab" s3 = str.rjust(20,"123")     # "12312312Captain Ahab"





The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net