有没有办法获取当前分配给对象的变量名称,例如使用对象 ID?
class Example
end
ex1 = Example.new
ex1.object_id
> 70184576592420
ex2 = ex1
也许它看起来像这样:
obj_id(70184576592420).var_names
> [ex1, ex2]
我会扩展@sagarpandya82答案:
local_variables.select do |e|
binding.local_variable_get(e).object_id == 70184576592420
end
#=> [:ex2, :ex1]
Just local_variables
返回所有局部变量的列表。