tags:

views:

47

answers:

2

Why does Kernel#p print to standard out? Isn't printf debugging supposed to output to standard error?

+1  A: 

Why are you assuming Kernel#p is intended for debugging? It writes to stdout just like Kernel#print or printf in C.

If you want to write to standard error you could do:

$stderr.puts(x.inspect)

By the way, if you really want to use printf debugging I suggest you read this article about debugging techniques

Firas Assaad
Don't you mean `$stderr.puts(x.inspect)`?
Andrew Grimm
If you want the behavior of Kernel#p, yes.
Firas Assaad
+1  A: 

You can define a global function "q", which works just like "p" except it prints to $stderr.

#!/usr/bin/ruby1.8

module Kernel

  def q(*stuff)
    stuff.each { |thing| $stderr.print(thing.inspect + "\n")}
  end

end

q 'foo'    # => "foo"

You may be tempted to use puts instead of print ... + "\n". This code uses print to make it thread-safe: puts can be interrupted between the time it prints its arguments and the time it prints the new-line, causing output from two threads to appear on one line. It's seldom that you have code from multiple threads writing to $stdout/$stderr at the same time, so it's not usually an issue. But this being a debugging tool, you will certainly end up using it to find out what is going on in threads.

Wayne Conrad