从对象访问变量的名称 [英] Accessing a variable's name from an object
本文介绍了从对象访问变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个对象:
object_name = "hello"
有没有办法获得变量的名称"object_name"
?我需要创建一个带有变量名称和其中值的字符串,例如
is there any way to get the variable's name "object_name"
? I need to create a string with the variable's name and the value in it, e.g.
"The name of the variable is 'object_name' and its value is 'hello'"
我试过了:
object_name.object_id
# => 20084556
推荐答案
def find_var(in_binding, object_id)
name = in_binding.local_variables.find do |name|
in_binding.local_variable_get(name).object_id == object_id
end
[name, in_binding.local_variable_get(name)]
end
the_answer = 42
find_var binding, the_answer.object_id # => [:the_answer, 42]
foo = 'bar'
baz = [foo]
find_var binding, baz.first.object_id # => [:foo, "bar"]
明显的失败 - 两个变量指向同一个对象.阿卡
Obvious downfall - two variables pointing to the same object. Aka
a = b = 42
这篇关于从对象访问变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文