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?

···

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

try v.intern.to_s

···

------------------------------------------
Daniel Brumbaugh Keeney
Devi Web Development
Devi.WebMaster@gMail.com
------------------------------------------

On 9/7/07, Todd A. Jacobs <tjacobs-sndr-019fdb@codegnome.org> wrote:

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"

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

···

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?

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.

···

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

try v.intern.to_s

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