Accessing variable names in ruby

T

Todd A. Jacobs

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?
 
T

Todd A. Jacobs

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.
 
R

Robert Klemme

2007/9/7 said:
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?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,731
Latest member
MarcyGipso

Latest Threads

Top