@instance_variable 和 attr_accessor 的区别 [英] Difference between @instance_variable and attr_accessor
问题描述
我刚开始学习 ruby,我没有看到 @instace_variable
和使用 attr_accessor
声明的属性之间的区别.
I Just started learning ruby and I don't see the difference between an @instace_variable
and an attribute declared using attr_accessor
.
以下两个类有什么区别:
What is the difference between the following two classes:
class MyClass
@variable1
end
和
class MyClass
attr_accessor :variable1
end
我在网上搜索了很多教程,每个人都使用不同的符号,它与ruby版本有什么关系吗?我还在 StackOverflow 中搜索了几个旧线程
I searched lot of tutorials online and everybody uses different notation, Does it have to do anything with the ruby version? I also searched few old threads in StackOverflow
Ruby 中的 attr_accessor 是什么?
这两个 Ruby 类初始化定义有什么区别?
但我仍然不知道什么是最好的使用方式.
But still I am not able to figure out what is the best way to use.
推荐答案
实例变量在它所在的对象之外不可见;但是当您创建一个 attr_accessor
时,它会创建一个实例变量,并使其在对象外可见(和可编辑).
An instance variable is not visible outside the object it is in; but when you create an attr_accessor
, it creates an instance variable and also makes it visible (and editable) outside the object.
实例变量示例(不是attr_accessor
)
class MyClass
def initialize
@greeting = "hello"
end
end
m = MyClass.new
m.greeting #results in the following error:
#NoMethodError: undefined method `greeting' for #<MyClass:0x007f9e5109c058 @greeting="hello">
使用attr_accessor
的示例:
class MyClass
attr_accessor :greeting
def initialize
@greeting = "hello"
end
end
m2 = MyClass.new
m2.greeting = "bonjour" # <-- set the @greeting variable from outside the object
m2.greeting #=> "bonjour" <-- didn't blow up as attr_accessor makes the variable accessible from outside the object
希望能说明一切.
这篇关于@instance_variable 和 attr_accessor 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!