liveBook · Manning

Puts

As explained in The Well-Grounded Rubyist, Fourth Edition

puts is a Ruby output method that writes objects to an IO stream and normally appends a newline after each line.

puts is Ruby’s everyday output method. It writes a value to an output stream and normally appends a newline, making each printed line begin after the previous one. If the value already ends with a newline, puts does not add another. section 1.1.6

Use puts to produce readable line-oriented output:

  • puts can write calculated values as well as strings. section 1.1.6
  • Use print when adjacent output must remain on the same line; a trailing newline must then be supplied explicitly. section 1.1.6
  • Calling puts on an open file handle, such as fh.puts fahrenheit, writes the value to that file rather than the screen. section 1.1.7
  • In irb, puts displays its output and returns nil, so irb may show both the printed line and => nil. section 1.4.2

Printing a conversion result

celsius = gets.to_i fahrenheit = (celsius * 9 / 5) + 32 puts "The Fahrenheit equivalent is #{fahrenheit}." section 1.1.7

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains newline handling, contrasts print, demonstrates file handles, and notes the nil return value in irb.
Examples
Uses a Celsius-to-Fahrenheit converter, screen output, file output, and an irb Hello example.
What it assumes
Assumes basic Ruby expressions and variables while demonstrating output alongside input, arithmetic, and file handles.
What you can do after
Apply it via Ruby to produce newline-terminated screen output or write calculated values through a file handle.
How it connects
Connects puts with print, p, gets, file input and output, method calls, and irb expression evaluation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.