【发布时间】:2013-08-21 13:13:53
【问题描述】:
在我展开我的问题之前,让我声明我已经阅读了问题here、here 和here 的答案。因此,要求您不要将我的问题标记为与这些答案重复的问题并没有让我理解attr_accessor 的目的。我的问题更多与逻辑有关,而不是语法。
我在下面创建了两组代码。这些集合彼此相同,只是其中一个集合根本没有attr_accessor 行。当我运行两组时,它们都给了我相同的输出。那么,从逻辑上讲,当两组代码给我相同的预期输出时,attr_accessor 行有什么区别?
代码集 1:
class Animal
def initialize(name)
@name = name
end
end
class Cat < Animal
def talk
"Meaow!"
end
end
class Dog < Animal
def talk
"Woof!"
end
end
animals = [Cat.new("Flossie"), Dog.new("Clive"), Cat.new("Max")]
animals.each do |animal|
puts animal.talk
end
#Output:
#Meaow!
#Woof!
#Meaow!
代码集 2:
class Animal
attr_accessor :name #this line is the only difference between the two code sets.
def initialize(name)
@name = name
end
end
class Cat < Animal
def talk
"Meaow!"
end
end
class Dog < Animal
def talk
"Woof!"
end
end
animals = [Cat.new("Flossie"), Dog.new("Clive"), Cat.new("Max")]
animals.each do |animal|
puts animal.talk
end
#Output:
#Meaow!
#Woof!
#Meaow!
两组代码都调用 Animal 类来创建具有名称的动物对象的新实例。我强调“……有名字”。因为 attr_accessor (在第二组中)定义了 :name 属性。但是在第一个代码集中,我删除了attr_accessor,但仍然设法创建具有名称属性的对象实例。
【问题讨论】:
标签: ruby class oop attr-accessor