A tap() for debugging

#1

Hello,

I use often things like ...tap {|a| p a}....
So I propose ‘dp’ methods ( ‘debug print’ ) in Object class.

Usage :

l=%w{1 2 3 4 5 6 7 8 9 10}
l.map {|a| a.to_i}.dp("after convertion").
  select {|a| a>3}.dp("after select").
  map {|a| a*a}.
  sort_by {|a| a.to_s.size }.
  dp

Output :

after convertion : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
after select : [4, 5, 6, 7, 8, 9, 10]
DP: a.rb:21 : [25, 36, 49, 64, 81, 16, 100]

Finaly, the dp() method :

class Object
	def dp(comment=nil)
	   return self unless $DEBUG
	   out=if comment
	      "#{comment} : #{self.inspect}"
	   else
	     "DP: %s : %s" % [caller.first.split(":",3)[0,2].join(":"),self.inspect]
	   end
	   puts out
	   self
	end
end
1 Like