How is STDERR.puts different from puts in Ruby?

rubynewbie picture rubynewbie · Mar 10, 2014 · Viewed 38k times · Source

I'm learning the language from Programming Ruby 1.9, and they toss STDERR.puts into a block of code early in the book without explaining why they're using it or how it's different from puts.

I've googled and wikied the term, but all I can gather from my research is that it's involved in diagnostics. Nowhere in the code provided by Programming Ruby does there seem to be a link to error exception handling.

Here's the code.

require_relative 'csv_reader'
reader = CsvReader.new
ARGV.each do |csv_file_name|
  STDERR.puts "Processing #{csv_file_name}"
  reader.read_in_csv_data(csv_file_name)
end

I did manage to read somewhere that STDERR.puts is used for error handling out of convention, but I guess I'm asking if it acts any differently than puts.

Answer

Palpatim picture Palpatim · Mar 10, 2014

By default, puts writes to STDOUT. By specifying STDERR.puts, you're sending your output to the STDERR handle. Although the implementation behavior is the same, using STDERR instead of STDOUT will definitely impact consumers of your program, since they will be attempting to capture output from your program from STDOUT, by convention. Best practice is to log debugging information, errors, warnings, status, etc to STDERR and actual program output to STDOUT.