Ruby Logging Method

I need a ruby ​​method that does this:

anyobject.show

call output will be:

anyvar => _the_ _pp_ _string_ _of_ _the_ _object_ 

Something close, but not quite so:

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

Since you need to type "anyvar" to accomplish this.

+3
source share
3 answers

In general, this is not possible because methods are invoked as objects, not variables.

Edit:

If you want to do this with a "function" and not with a method, you can add this to the kernel:

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

and call him through

show "anyvar"

This is a little ugly due to the need to pass the variable name as a string, of course.

+1
source

That should do what you ask. It prints readable information about the object in YAML format:

puts YAML::dump(object)

, show :

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

:

require 'yaml'
+3

:

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
+2

Source: https://habr.com/ru/post/1718687/


All Articles