【问题标题】:What's the purpose of the 'attr_accessor' in creating objects in Ruby? [duplicate]'attr_accessor' 在 Ruby 中创建对象的目的是什么? [复制]
【发布时间】:2013-08-21 13:13:53
【问题描述】:

在我展开我的问题之前,让我声明我已经阅读了问题hereherehere 的答案。因此,要求您不要将我的问题标记为与这些答案重复的问题并没有让我理解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


    【解决方案1】:

    attr_accessor :attribute_name 是以下的简写:

    def attribute_name
      @attribute_name
    end
    
    def attribute_name=(value)
      @attribute_name = value
    end
    

    它用于设置实例变量。在您的代码片段中,您直接在initialize 方法中设置实例变量,因此您不需要attr_accessor

    【讨论】:

    • 如果您想通过方法调用再次分配(或修改)attribute_name 变量,您仍然可能需要 attr_accessor。
    【解决方案2】:

    实例变量始终可以在您的代码演示的实例方法中读取/写入。 attr_accessor 使实例变量在类外部 可读/可写(通过定义访问器方法)。通过将其添加到您的第二个示例中,您允许以下操作:

    cat = Cat.new("Garfield")
    puts cat.name
    cat.name = "Maru"
    

    这将在您的第一个示例中引发 NoMethodError

    【讨论】:

    • 谢谢 Max,这正是我需要的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2013-01-31
    • 2011-08-04
    相关资源
    最近更新 更多