I want to write a simple debug method in Ruby for my Rails app:
foo = "bar"
debug(foo)
The debug method would return the string "foo: bar"
.
How do you get the name of the object (foo, in this case) in Ruby?
Working in Ruby 1.92.
Thanks.
I want to write a simple debug method in Ruby for my Rails app:
foo = "bar"
debug(foo)
The debug method would return the string "foo: bar"
.
How do you get the name of the object (foo, in this case) in Ruby?
Working in Ruby 1.92.
Thanks.
check out log_buddy
from the readme:
a = "foo"
@a = "my var"
@@bar = "class var!"
def bark
"woof!"
end
d { a } # logs "a = 'foo'"
d { @a } # logs "@a = 'my var'"
d { @@bar } # logs "@@bar = 'class var!'"
d { bark } # logs "bark = woof!"
def debug(var,val)
puts "#{var}: #{val}"
end
debug("foo",foo)
For completeness, here's a way you should not do it. This is a horrible idea, and will break in all kinds of ways:
According to Chris Shea, Section 8.6 in The Ruby Programming Language by Flanagan and Matz has this snippet (comments added for clarity):
class Object
def get_name #do not use this brittle technique
line_number = caller[0].split(':')[1].to_i
line_executed = File.readlines(__FILE__)[line_number-1]
line_executed.match(/(\S+)\.get_name/)[1] #BAD IDEA: parsing Ruby with regular expressions
end
end
It "works" by finding the line number at which get_name
was called, reading that line from the currently running file, and attempting to use a regular expression to parse out the name of the variable. With apologies to Zalgo, do not try to parse Ruby with regular expressions!
I'm not sure you could reliably do this, particularly across Ruby implementations. What's your main goal in doing this? To eliminate manual generation of semantic information?
As others have stated, just printing a variable name isn't necessarily helpful on its own: without context, it may not be any more helpful than dumping the variable.
Seems like a better idea would be to use the normal logging mechanisms, and provide contextually-meaningful information along with symbol values.
Or just use pry.
As usual with Ruby, there's a gem for that: http://thinkrelevance.com/blog/2009/09/23/quick-and-easy-logging-with-logbuddy.html
It will output to stdout.
Thanks to Andrew Grimm (above) and Leventix.