有没有办法通过使用对象ID来获取当前分配给对象的变量名称?
class Example
end
ex1 = Example.new
ex1.object_id
> 70184576592420
ex2 = ex1
也许它看起来像这样:
obj_id(70184576592420).var_names
> [ex1, ex2]
答案 0 :(得分:4)
我会延伸@ sagarpandya82回答:
local_variables.select do |e|
binding.local_variable_get(e).object_id == 70184576592420
end
#=> [:ex2, :ex1]
只需local_variables
即可返回所有本地变量的列表。