1

クラスのメソッドを理解するのに苦労し、インスタンスに属性を正しく表示できない理由を理解するのに苦労しています。

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 属性が表示されません。コード内で何らかの形で誤ってラベル付けしたためだと思います。

4

2 に答える 2

3

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

これにより、クラス自体ではなく、新しいインスタンスに属性が設定されます。

于 2012-04-28T19:02:40.113 に答える
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

于 2012-04-28T19:02:47.583 に答える