Accessing variable names in ruby

I found myself trying to do a bit of ruby debugging, and was going crazy
trying to figure out how to display a variable’s name instead of its
value in a string. There may be a more elegant way, but I found that
symbols did what I wanted:

if $DEBUG

[:my_email, :my_resume, :my_logfile].each do |v|
$stderr.puts “DEBUG: #{v} = #{eval v.to_s}”
end
end

Is there a better way?

try v.intern.to_s


Daniel Brumbaugh K.
Devi Web D.
[email protected]

On Sat, Sep 08, 2007 at 09:01:56AM +0900, Devi Web D. wrote:

try v.intern.to_s

That doesn’t work with symbols (raises “NoMethodError: undefined method
`intern’ for :my_email:Symbol” ), and just returns the value of the
variable (not the variable name) when used with a variable instead of a
symbol.

2007/9/7, Todd A. Jacobs [email protected]:

Is there a better way?

When you use %w you can easily use strings for this. I’d also use
#inspect as it is generally better for debugging purposes:

%w[my_email my_resume my_logfile].each do |v|
$stderr.puts “DEBUG: #{v} = #{eval(v).inspect}”
end if $DEBUG

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs