2012-04-28 10 views
1

ここでは、クラスメソッドを理解するのが苦労し、なぜインスタンスで正しく表示される属性を取得できないのですか。私はクラスメソッドcreate_with_attributesを(animal.2上)を使用する場合クラスメソッド(ルビー)

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 

は、私はときに私puts animal2.color"white"が現れることを期待しています。

「ノイズ」があるようにattr_accessorを使用して定義したようですが、ノイズは正しく表示されますが、色は正しく表示されません。このプログラムを実行するとエラーは発生しませんが、.color属性は表示されません。私はそれが何とか間違ってコードに表示されているためだと思います。

答えて

3

self.create_with_attributesのでは、インスタンス変数を設定していないが、代わりに何がclass instance variableとして知られているその中に@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 

をクラスそのものの

+0

ご協力いただきありがとうございます。私は壁に向かって頭を叩いていたので、あなたは私にとってそれをとても明確にしました。とても有難い!!! –

+0

私が正しく理解しているのは、noise属性がanimal.2に表示された理由よりも、インスタンス変数を設定していたInitializeメソッドで設定したためです。 –

+0

'initialize'メソッドはノイズを必要とするので、' self.create_with_attributes'の 'animal.noise = noise'行は、すでに設定されているので実際には必要ありません。 – x1a4

1

create_with_attributesメソッドを使用している場合、インスタンス変数はAnimalのインスタンスではなく、Animalクラス自体に設定されます。これは、メソッドがAnimalクラス(Classのインスタンス)にあり、したがって、そのコンテキスト内で実行され、Animalのインスタンスのコンテキストでは実行されないためです。次のようにすると:"white"が返されます。

Animal.instance_variable_get(:@color) 

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

それはとにかくあなたのinitializeで行われていますので、私はnoiseの設定を削除:あなたが代わりにあなたがちょうどそうのようなsetterメソッドを呼び出すことにより、作成したインスタンスの属性を設定する必要がある、と述べ

+0

「ノイズ」の設定を削除することについての最後の注意を追加してくれてありがとう。それは何が起こっているか私に非常に明確にしました。 –