获取类中声明的所有实例变量 [英] Get all instance variables declared in class
本文介绍了获取类中声明的所有实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请帮助我以相同的方式获取类中声明的所有实例变量instance_methods
显示类中所有可用的方法.
Please help me get all instance variables declared in a class the same way instance_methods
shows me all methods available in a class.
class A
attr_accessor :ab, :ac
end
puts A.instance_methods #gives ab and ac
puts A.something #gives me @ab @ac...
推荐答案
您可以使用 instance_variables
:
You can use instance_variables
:
A.instance_variables
但这可能不是您想要的,因为它获取的是 class A
中的实例变量,而不是该类的实例.所以你可能想要:
but that’s probably not what you want, since that gets the instance variables in the class A
, not an instance of that class. So you probably want:
a = A.new
a.instance_variables
但请注意,仅调用 attr_accessor
并没有定义任何实例变量(它只是定义了方法),因此在您明确设置它们之前,实例中不会有任何实例变量.
But note that just calling attr_accessor
doesn’t define any instance variables (it just defines methods), so there won’t be any in the instance until you set them explicitly.
a = A.new
a.instance_variables #=> []
a.ab = 'foo'
a.instance_variables #=> [:@ab]
这篇关于获取类中声明的所有实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文