Ruby Programming Language

Formatted Output

By

First published on August 23, 2019. Last updated on February 13, 2020.


There are ways to more nicely format screen output for Ruby. Typically, we will create a statement that will tell Ruby to format output into columns of specified sized. We can also use tabs to align the columns. Below is an example of code to nicely-formatted output.

The trick to nicely-formatted output is to create a string expression with formatting information. Below, that expression is to the right of the periodstringvariable. Here is what each part does:

  • %2d produces a fixed number column with a width of 2.
  • \t tabs the output to the right.
  • %11.3f creates a floating number column that is eleven characters wide with three digits after the decimal place.

The puts sprintfcode then prints the variables to its right using the format expression. Note: the number of columns in the expression must match the number of variables after sprintf.

# display variables with type conversions
per = period.to_s
lin = lineargrowth.to_s
exp = exponentialgrowth.to_s
periodstring = (”%2d\t\t%11.3f\t\t%1.3f”)
puts sprintf periodstring , per , lin ,exp
It can be difficult to fit the full variable names after the sprintf command without going to another line. So short versions of the variable names are created, such as:

 per, lin, exp.

The above code will produce output in formatted, consistently-spaced columns.


COURSE


Content is copyright the author. Layout is copyright Mark Ciotola. See Corsbook.com for further notices.