ruby 从类外部访问实例变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12122736/
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
Access instance variable from outside the class
提问by Pawan
If an instance variable belongs to a class, can I access the instance variable (e.g. @hello) directly using the class instance?
如果实例变量属于一个类,我可以@hello使用类实例直接访问实例变量(例如)吗?
class Hello
def method1
@hello = "pavan"
end
end
h = Hello.new
puts h.method1
回答by knut
Yes, you can use instance_variable_getlike this:
是的,你可以这样使用instance_variable_get:
class Hello
def method1
@hello = "pavan"
end
end
h = Hello.new
p h.instance_variable_get(:@hello) #nil
p h.method1 #"pavan" - initialization of @hello
p h.instance_variable_get(:@hello) #"pavan"
If the variable is undefined (first call of instance_variable_getin my example) you get nil.
如果变量未定义(instance_variable_get在我的例子中第一次调用),你会得到nil.
As Andrew mention in his comment:
正如安德鲁在他的评论中提到的:
You should not make this the default way you access instance variables as it violates encapsulation.
您不应将此作为访问实例变量的默认方式,因为它违反了封装。
A better way is to define an accessor:
更好的方法是定义一个访问器:
class Hello
def method1
@hello = "pavan"
end
attr_reader :hello
end
h = Hello.new
p h.hello #nil
p h.method1 #"pavan" - initialization of @hello
p h.hello #"pavan"
If you want another method name, you could aliasthe accessor: alias :my_hello :hello.
如果您想要另一个方法名称,您可以为访问器取别名:alias :my_hello :hello。
And if the class is not defined in your code, but in a gem: You can modify classesin your code and insert new functions to classes.
如果类不是在您的代码中定义的,而是在 gem 中定义的:您可以修改代码中的类并将新函数插入到 classes 中。
回答by Kevinvhengst
You can also accomplish this by calling attr_readeror attr_accessorlike this:
您也可以通过调用attr_reader或attr_accessor像这样来完成此操作:
class Hello
attr_reader :hello
def initialize
@hello = "pavan"
end
end
or
或者
class Hello
attr_accessor :hello
def initialize
@hello = "pavan"
end
end
Calling attr_readerwill create a getterfor the given variable:
调用attr_reader将为getter给定变量创建一个:
h = Hello.new
p h.hello #"pavan"
Calling attr_accessorwill create a getterAND a setterfor the given variable:
调用attr_accessor将为给定变量创建一个getterAND a setter:
h = Hello.new
p h.hello #"pavan"
h.hello = "John"
p h.hello #"John"
As you might understand, use attr_readerand attr_accessoraccordingly. Only use attr_accessorwhen you need a getterAND a setterand use attr_readerwhen you only need a getter
正如您可能理解的那样,使用attr_reader并attr_accessor相应地。仅attr_accessor在需要getterAND a 时setter使用attr_reader,仅在需要时使用getter

