views:

99

answers:

3

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.

+1  A: 

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.

Martin DeMello
I changed the brackets a bit:def show(var) print "#{var} => #{eval(var).pretty_inspect}"endI tried an irb session with a = 1 ; then show ("a") ; and it returned "nil" for your version , and "a is an undefined variable" for my version. $a = 1 ; show ("$a") ; however, did work. This is a clever - but is there a scope issue (does not work for local variables ). ?
Gush
You need to pass the binding of the current context to the `show` method: `def show(var,b); print "#{var} => #{eval(var,b).pretty_inspect}"; end` and then `show "anyvar", binding`
glenn jackman
+3  A: 

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'
rogeriopvl
no it doesnt. At least not in irb:>> a = "asdf"=> "asdf">> puts YAML::dump(a)--- asdf=> nil
Gush
+1  A: 

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
khelll
You're not passing the variable name
glenn jackman
oops!, modified
khelll
i think var name needs to be quoted
Gush