获取局部变量的名称 [英] Get The Name Of A Local Variable

查看:49
本文介绍了获取局部变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开发时&调试,有时我希望我可以写一个 1-liner 来转储名称、类型和一堆变量的值.问题是我根本不知道如何访问变量的名称.

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.

这是第一次尝试:

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?

推荐答案

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

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

但是,如果您想要一个带有 1 个参数的方法,这当然对您没有帮助.

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

这篇关于获取局部变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆