新手在这里,很难理解类方法以及为什么我无法在实例中正确显示属性。
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上)时,我希望"white"
出现puts animal2.color
。
似乎我使用attr_accessor
定义它就像我有“噪音”一样,然而噪音正确显示而颜色则不然。运行此程序时,我没有收到错误,但.color属性没有出现。我相信这是因为我在代码中以某种方式错误地标记了它。
答案 0 :(得分:3)
self.create_with_attributes
是一种类方法,因此在其中设置@noise
和@color
not 设置实例变量,而不是所谓的{{ 3}}
您要做的是在您刚刚创建的实例上设置变量,因此请将self.create_with_attributes
更改为:
def self.create_with_attributes(noise, color)
animal = self.new(noise)
animal.noise = noise
animal.color = color
animal
end
将在新实例上设置属性,而不是在类本身上设置属性。
答案 1 :(得分:1)
当您使用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
。