クラスのメソッドを理解するのに苦労し、インスタンスに属性を正しく表示できない理由を理解するのに苦労しています。
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 で)クラス メソッドを使用すると、 I の"white"
ときに表示されることが期待されますputs animal2.color
。
「ノイズ」と同じように定義しattr_accessor
たように見えますが、ノイズは正しく表示されますが、色は表示されません。このプログラムを実行してもエラーは発生しませんが、.color 属性が表示されません。コード内で何らかの形で誤ってラベル付けしたためだと思います。