Last Updated: February 25, 2016
·
502
· nilmethod

Simple Print Debug Method in Ruby

Here's a simple way to avoid a lot of repetition in print debugging:

DEBUG = true
def debug(msg, obj = nil)
  msg = ("== DEBUG: #{msg}") unless (msg.class != String)
  $stderr.puts msg if DEBUG
  $stderr.puts obj if (DEBUG && obj != nil)
end

Sample usage:

irb(main):006:0> h = {:foo => "bar", :baz => "quux"}
=> {:foo=>"bar", :baz=>"quux"}

irb(main):007:0> debug "i'm a debug statement"
== DEBUG: i'm a debug statement

irb(main):008:0> debug "here's a hash", h
== DEBUG: here's a hash
{:foo=>"bar", :baz=>"quux"}