Gush
Gush

Reputation: 319

ruby logging convenience method

I would like a ruby method "show" which does this:

anyobject.show

the output of the call would be:

anyvar => _the_ _pp_ _string_ _of_ _the_ _object_ 

Something close , but not quite is :

p "any_var => #{any_var.pretty_inspect}"

Since you have to type "anyvar" out to accomplish that.

Upvotes: 3

Views: 243

Answers (3)

Martin DeMello
Martin DeMello

Reputation: 12336

In general, this can't be done because methods are called on objects, not variables.

Edit:

If you're willing to do it with a "function" rather than a method you could add this to Kernel:

def show(var)
  print "#{var} => #{eval(var).pretty_inspect}"
end

and call it via

show "anyvar"

It's a bit ugly because of the need to pass the variable name in as a string, of course.

Upvotes: 1

khelll
khelll

Reputation: 24000

A little enhanced version of Martin's one:

require 'pp'
def show(var,bindings) 
  print "#{var} => #{eval('var',bindings).pretty_inspect}"
end

a,t = 1,Time.now
show a,binding #=> a => 1
show t,binding #=> t => Mon Sep 28 13:12:34 +0300 2009

Upvotes: 2

rogeriopvl
rogeriopvl

Reputation: 54056

This should do what you're asking. It prints readable info about an object in YAML format:

puts YAML::dump(object)

So your show method would look like this:

def show:
  puts YAML::dump(self)
end

and don't forget to:

require 'yaml'

Upvotes: 3

Related Questions