ruby 获取类中声明的所有实例变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11925855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get all instance variables declared in class
提问by Akshay Vishnoi
Please help me get all instance variables declared in a class the same way instance_methodsshows me all methods available in a class.
请帮助我获取在类中声明的所有实例变量,以同样的方式instance_methods向我显示类中可用的所有方法。
class A
attr_accessor :ab, :ac
end
puts A.instance_methods #gives ab and ac
puts A.something #gives me @ab @ac...
回答by Andrew Marshall
You can use instance_variables:
您可以使用instance_variables:
A.instance_variables
but that's probably not what you want, since that gets the instance variables in the classA, not an instance of that class. So you probably want:
但这可能不是您想要的,因为它获取的是class 中的实例变量A,而不是该类的实例。所以你可能想要:
a = A.new
a.instance_variables
But note that just calling attr_accessordoesn't define any instance variables (it just defines methods), so there won't be any in the instance until you set them explicitly.
但请注意,只是调用attr_accessor并没有定义任何实例变量(它只是定义了方法),因此在您明确设置它们之前,实例中不会有任何实例变量。
a = A.new
a.instance_variables #=> []
a.ab = 'foo'
a.instance_variables #=> [:@ab]
回答by Aschen
If you want to get all instances variables values you can try something like this :
如果您想获取所有实例变量值,您可以尝试以下操作:
class A
attr_accessor :foo, :bar
def context
self.instance_variables.map do |attribute|
{ attribute => self.instance_variable_get(attribute) }
end
end
end
a = A.new
a.foo = "foo"
a.bar = 42
a.context #=> [{ :@foo => "foo" }, { :@bar => 42 }]
回答by Adam Strickland
It's not foolproof - additional methods could be defined on the class that match the pattern - but one way I found that has suited my needs is
这不是万无一失的 - 可以在与模式匹配的类上定义其他方法 - 但我发现适合我需要的一种方法是
A.instance_methods.grep(/[a-z_]+=/).map{ |m| m.to_s.gsub(/^(.+)=$/, '@') }
回答by Obromios
If you want to get a hash of all instance variables, in the manner of attributes, following on from Aschen's answer you can do
如果您想以属性的方式获取所有实例变量的哈希值,请按照 Aschen 的回答进行操作
class A
attr_accessor :foo, :bar
def attributes
self.instance_variables.map do |attribute|
key = attribute.to_s.gsub('@','')
[key, self.instance_variable_get(attribute)]
end.to_h
end
end
a = A.new
a.foo = "foo"
a.bar = 42
a.context #=> {'foo' => 'foo', 'bar' => 42}

