Ruby:
Printing debug output

How to:

In Ruby, puts and p are your go-to methods for quick output to the console.

def who_said_what
  quote = "To be or not to be"
  author = "Shakespeare"
  puts "Quote: #{quote}"
  p "Said by: #{author}"
end

who_said_what

Sample output:

Quote: To be or not to be
"Said by: Shakespeare"

The puts method prints a human-readable output, adding a new line at the end. In contrast, p prints the value in a more raw form, useful when you need to see if something’s a string or not.

Deep Dive

Back before fancy IDEs, printing to the console was debugging. It’s an old but gold technique, especially when you want to avoid the overhead of setting up a debugger.

As alternatives, you can use pp for pretty-printing complex objects, or gem libraries like awesome_print for enhanced readability. If your debug output is getting too chatty, consider a logging library to control levels of verbosity.

Implementation-wise, puts and p write to $stdout, a global I/O stream in Ruby. Output can be redirected if needed. Remember, while these methods are convenient, excessive debug prints can clutter your console and make debugging harder.

See Also