B Seven
B Seven

Reputation: 45943

How to get the name of an object in Ruby?

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.

Upvotes: 2

Views: 290

Answers (5)

B Seven
B Seven

Reputation: 45943

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.

Upvotes: 0

Matt Briggs
Matt Briggs

Reputation: 42178

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!"

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160181

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.

Upvotes: 0

daxelrod
daxelrod

Reputation: 2589

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!

Upvotes: 1

glenn mcdonald
glenn mcdonald

Reputation: 15488

def debug(var,val)
  puts "#{var}: #{val}"
end

debug("foo",foo)

Upvotes: 2

Related Questions