Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 134 ยท Getting Started

Reading Input and Formatting Output

Read input with gets and STDIN, print with puts, print, p and pp, and format numbers and tables with format, printf and the percent operator in Ruby.

A program that cannot talk to anyone is not very useful. In Ruby, input arrives from standard input (the keyboard or a pipe) and output leaves through standard output (the terminal) and standard error (for messages about problems). This lesson covers reading lines with gets, reading everything at once, the differences between puts, print, p and pp, and how to format numbers and tables with format, printf and the % operator.

The runner on this site has no keyboard, so every example that reads input has its input text preset in the editor's "Program input" box. In a real terminal the same code waits for you to type.

Printing: puts, print, p and pp

Ruby Four ways to print

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

  • puts converts each argument with to_s, adds a newline unless the text already ends with one, and flattens arrays.
  • print writes exactly what you give it and no newline.
  • p writes inspect, the programmer-friendly form with quotes around strings and a colon on symbols. It returns its argument, which makes it easy to drop into the middle of an expression while debugging.
  • pp is "pretty print": like p, but it breaks long structures over several lines so you can read them.

Use puts for output meant for people, p for debugging, and pp for large nested data:

Ruby pp wraps wide data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

When the structure fits in 80 columns pp prints it on one line, just like p. When it does not, pp puts each key on its own line with indentation. Your own classes can control how they appear in p and pp by defining inspect (see to_s, inspect and Conversions).

Standard error and warn

Diagnostics belong on standard error, so they do not get mixed with real output when someone redirects your program into a file.

Ruby stdout and stderr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

$stdout and $stderr are global variables holding the current streams; STDOUT and STDERR are the original constants. The runner shows both streams together.

Reading a line with gets

gets reads one line from standard input, including the newline, and returns nil at the end of input. That is why you nearly always see gets.chomp.

Ruby Reading a name and an age

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

to_i on a line like "36\n" ignores the trailing newline, so no chomp is needed there. When the input ends early, gets returns nil and calling a method on it raises an error:

Ruby gets returns nil at end of input (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The second gets has nothing to read, so it returns nil and the program stops with main.rb:4:in '<main>': undefined method 'chomp' for nil (NoMethodError). The robust forms are gets&.chomp or (gets || "").chomp, or reading until nil in a loop.

Reading until the input ends

Ruby Looping over lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The parentheses around the assignment tell Ruby (and the reader) that you really mean =. A Ruby programmer might also write $stdin.each_line or STDIN.each_line:

Ruby STDIN.each_line and read

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

$stdin.read slurps everything left. readlines returns all remaining lines as an array (each with its newline, so use readlines(chomp: true) to strip them). The single call $stdin.each_line(chomp: true) { ... } is convenient for line-by-line processing. If you run a script as ruby script.rb file.txt, bare gets reads from the file named on the command line first (through ARGF), which is a gotcha: use $stdin.gets when you mean the keyboard.

Formatting with format, printf and %

puts "Price: #{price}" is fine until you need control: two decimals, a fixed width, leading zeros, aligned columns. A format string contains ordinary text plus placeholders that start with %.

Ruby Format directives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The pieces of a directive are %[flags][width][.precision]type. Common types: d (integer), f (float), s (string via to_s), p (via inspect), x/o/b (bases), e (scientific). Flags: - left-align, 0 zero pad, + always show sign, space reserves room for a sign. Ruby's format has no thousands-separator flag; the last line shows what happens (format("%,d", 1000) raises an ArgumentError, which the rescue modifier turns into a message). A common trick for thousands separators is n.to_s.reverse.scan(/\d{1,3}/).join(",").reverse.

printf is print(format(...)), and String#% is the same as format with the string on the left:

Ruby printf, % and named references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Named references (%<name>s or %{name}) make long templates readable and survive reordering, and they take a hash. Positional ones (%2$s) are useful when translated text changes word order.

Building a report

Putting it together, here is a small table with aligned columns, computed totals and a footer.

Ruby A formatted receipt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice that header.length is used to size the rules, so the table stays consistent if you change a width. Money in real programs should use integer cents or BigDecimal rather than Float; see Numbers.

Heredocs and puts for multi-line output

For longer text, a heredoc keeps the program readable. It combines nicely with format through %:

Ruby A heredoc template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Practical advice

  • Always chomp lines you read, unless you are only calling to_i or to_f.
  • Test for nil from gets if the input might end early.
  • Output for humans: puts and format. Debugging: p and pp. Errors and logs: warn or $stderr.
  • Use $stdin rather than bare gets when your script may also receive file names as arguments.
  • Buffering: output to a terminal is line-buffered, to a pipe it may be block-buffered. Call $stdout.flush or set $stdout.sync = true if prompts must appear immediately.
  • Format money and percentages with format, not with round alone: 3.5.round(2) prints 3.5, while format("%.2f", 3.5) prints 3.50.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which output method returns its argument, which is handy while debugging?

    p prints the inspect form and returns the object it was given, so you can wrap an expression in p(...) without changing the program. puts and print return nil.
  2. 2. What does gets return when the input has ended?

    gets returns nil at end of input. Calling chomp on it then raises NoMethodError, so check for nil or use gets&.chomp.
  3. 3. What does format("%05.1f", 3.14159) return?

    The width is 5 including the decimal point and one decimal, padded with zeros, so you get 003.1.
  4. 4. Why is $stdin.gets sometimes safer than a bare gets?

    Kernel#gets reads through ARGF, which treats command-line arguments as files to read. $stdin.gets always reads the standard input stream.
  5. 5. What does "%s is %d" % ["x", 5] return?

    String#% is a shortcut for format, with an array supplying several values.

Summary

  • puts prints text for people, print prints without a newline, p shows inspect and returns its argument, pp pretty-prints large structures.
  • Use warn or $stderr for diagnostics.
  • gets reads a line including the newline and returns nil at the end; chomp it, and guard against nil.
  • $stdin.read, readlines and each_line read the rest of the input.
  • format, printf and % control width, precision, padding, bases and named placeholders.
  • Prefer $stdin.gets when command-line file arguments could be in play.

Next: Operators