[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Accessing variable names in ruby

Todd A. Jacobs

9/7/2007 5:22:00 AM

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?

--
"Oh, look: rocks!"
-- Doctor Who, "Destiny of the Daleks"

2 Answers

Todd A. Jacobs

9/10/2007 5:20:00 PM

0

On Sat, Sep 08, 2007 at 09:01:56AM +0900, Devi Web Development 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.

--
"Oh, look: rocks!"
-- Doctor Who, "Destiny of the Daleks"

Robert Klemme

9/11/2007 8:46:00 AM

0

2007/9/7, Todd A. Jacobs <tjacobs-sndr-019fdb@codegnome.org>:
> 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