Ruby Programming Language

Formatted Output

By

First published on January 30, 2019


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.

[code lang=”ruby”]
# 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
[/code]

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

[code]per[/code]

,

[code]lin[/code]

and

[code]exp[/code]

.

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

 

 

 


| COURSE |


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