类方法(ruby)

这里有新手,很难理解类方法以及为什么我无法在实例中正确显示属性。

class Animal attr_accessor :noise, :color, :legs, :arms def self.create_with_attributes(noise, color) animal = self.new(noise) @noise = noise @color = color return animal end def initialize(noise, legs=4, arms=0) @noise = noise @legs = legs @arms = arms puts "----A new animal has been instantiated.----" end end animal1 = Animal.new("Moo!", 4, 0) puts animal1.noise animal1.color = "black" puts animal1.color puts animal1.legs puts animal1.arms puts animal2 = Animal.create_with_attributes("Quack", "white") puts animal2.noise puts animal2.color 

当我使用类方法create_with_attributes(在animal.2上)时,我希望当我puts animal2.color时会出现"white"

似乎我使用attr_accessor定义它就像我有“噪音”一样,然而噪音正确显示而颜色不会。 运行此程序时,我没有收到错误,但.color属性没有出现。 我相信这是因为我在代码中以某种方式错误地标记了它。

self.create_with_attributes是一个类方法,因此在其中设置@noise@color 不是设置实例变量,而是设置所谓的类实例变量 。

你想要做的是在你刚刚创建的实例上设置变量,所以改为将self.create_with_attributes改为:

  def self.create_with_attributes(noise, color) animal = self.new(noise) animal.noise = noise animal.color = color animal end 

这将在新实例上设置属性,而不是在类本身上设置属性。

当您使用create_with_attributes方法时,实例变量在Animal类本身上设置,而不是在您刚刚创建的Animal实例上设置。 这是因为该方法在Animal类(它是Class一个实例)上,因此它在该上下文中运行,而不是在任何Animal实例的上下文中运行。 如果你这样做:

 Animal.instance_variable_get(:@color) 

在运行你描述的方法之后,你应该得到"white"

也就是说,您需要通过调用setter方法来设置刚刚创建的实例上的属性,如下所示:

 def self.create_with_attributes(noise, color) animal = self.new(noise) animal.color = color return animal end 

我删除了noise设置,因为它在你的initialize完成了。