Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get The Name Of A Local Variable

Tags:

ruby

When developing & debugging, I sometimes wish I could write a 1-liner that dumped the names, types & values of a bunch of variables. The problem is I don't know how to access the name of a variable, if I can at all.

Here is a first attempt:

foo = 1
bar = "42"
baz = Hash.new

[foo, bar, baz].each do |v|
    puts "#{v.???} = (#{v.class}) #{v}"
    end

I'd like the output of this program to be something like:

foo = (Fixnum) 1 
bar = (String) 42 
baz = (Hash) ...

I don't know what ??? should be above. Can this be done?

like image 448
John Dibling Avatar asked Jul 14 '10 19:07

John Dibling


People also ask

How do I find the name of a variable in Python?

python-varname is not only able to detect the variable name from an assignment, but also: Retrieve variable names directly, using nameof. Detect next immediate attribute name, using will. Fetch argument names/sources passed to a function using argname.

Can we print variable name in Java?

In short. You can't print just the name of a variable.

Why are local variable names?

Why are local variable names beginning with an underscore discouraged? Explanation: As Python has no concept of private variables, leading underscores are used to indicate variables that must not be accessed from outside the class.


2 Answers

foo = 1
bar = "42"
baz = Hash.new

%w(foo bar baz).each do |vn|
    v = eval(vn)
    puts "#{vn} = (#{v.class}) #{v}"
end

But this, of course, doesn't help you if you want a method with 1 argument.

like image 141
Leventix Avatar answered Oct 12 '22 16:10

Leventix


Here's a little bit of debug code I use all over the place (I stick it in a separate file so that it can be required wherever needed). It can be used two ways. Passed one or more values, it simply inspects them and writes the result to $stderr. But passed a block which returns one or more things, it writes them out with their names.

#!/usr/bin/ruby1.8

def q(*stuff, &block)
  if block
    s = Array(block[]).collect do |expression|
      value = eval(expression.to_s, block.binding).inspect
      "#{expression} = #{value}"
    end.join(', ')
    $stderr.puts s
  else
    stuff.each do
      |thing| $stderr.print(thing.inspect + "\n")
    end
  end
end

i = 1
q i       # => 1
q {:i}    # => i = 1

name = "Fred"
q [name, name.length]         # => ["Fred", 4]
q {[:name, 'name.length']}    # => name = "Fred", name.length = 4

Note: The q function, and more, is now available in the cute_print gem.

like image 21
Wayne Conrad Avatar answered Oct 12 '22 16:10

Wayne Conrad