Paw*_*wan 78 ruby instance-variables
如果实例变量属于某个类,我可以@hello直接使用类实例访问实例变量(例如)吗?
class Hello
def method1
@hello = "pavan"
end
end
h = Hello.new
puts h.method1
Run Code Online (Sandbox Code Playgroud)
knu*_*nut 136
是的,你可以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"
Run Code Online (Sandbox Code Playgroud)
如果变量未定义(instance_variable_get在我的示例中首次调用),则得到nil.
安德鲁在评论中提到:
您不应该将此作为访问实例变量的默认方式,因为它违反了封装.
更好的方法是定义一个访问者:
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"
Run Code Online (Sandbox Code Playgroud)
如果你想要另一个方法名,你可以为访问者设置别名:alias :my_hello :hello.
如果类没有在您的代码中定义,而是在gem中定义:您可以修改代码中的类并将新函数插入到类中.
Kev*_*gst 12
您也可以通过调用attr_reader或attr_accessor像这样完成此操作:
class Hello
attr_reader :hello
def initialize
@hello = "pavan"
end
end
Run Code Online (Sandbox Code Playgroud)
要么
class Hello
attr_accessor :hello
def initialize
@hello = "pavan"
end
end
Run Code Online (Sandbox Code Playgroud)
调用attr_reader将为getter给定变量创建一个:
h = Hello.new
p h.hello #"pavan"
Run Code Online (Sandbox Code Playgroud)
调用attr_accessor将为给定变量创建getterAND a setter:
h = Hello.new
p h.hello #"pavan"
h.hello = "John"
p h.hello #"John"
Run Code Online (Sandbox Code Playgroud)
如你所知,使用attr_reader并attr_accessor相应地.仅attr_accessor在您需要getterAND 时setter使用attr_reader,并在您只需要时使用getter
| 归档时间: |
|
| 查看次数: |
64582 次 |
| 最近记录: |