October 2006
Intermediate to advanced
888 pages
16h 55m
English
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 ...
Read now
Unlock full access