Ruby でオブジェクトの配列を作成するには:
配列を作成し、名前にバインドします。
array = []
それにオブジェクトを追加します。
array << DVD.new << DVD.new
いつでも任意のオブジェクトを配列に追加できます。
クラスのすべてのインスタンスにアクセスしたい場合は、以下DVD
に頼ることができますObjectSpace
。
class << DVD
def all
ObjectSpace.each_object(self).entries
end
end
dvds = DVD.all
ところで、インスタンス変数が正しく初期化されていません。
次のメソッド呼び出し:
attr_accessor :title, :category, :run_time, :year, :price
attribute
/ instance メソッドを自動的に作成attribute=
して、インスタンス変数の値を取得および設定します。
initialize
定義されたメソッド:
def initialize
@title = title
@category = category
@run_time = run_time
@year = year
@price = price
end
引数を取らないにもかかわらず、インスタンス変数を設定します。効果的に起こることは次のとおりです。
attribute
リーダーメソッドが呼び出されます
- 未設定の変数を読み取ります
- 戻る
nil
nil
変数の値になります
あなたがしたいことは、変数の値をinitialize
メソッドに渡すことです:
def initialize(title, category, run_time, year, price)
# local variables shadow the reader methods
@title = title
@category = category
@run_time = run_time
@year = year
@price = price
end
DVD.new 'Title', :action, 90, 2006, 19.99
また、必要な属性がDVD
のタイトルのみの場合は、次の方法で行うことができます。
def initialize(title, attributes = {})
@title = title
@category = attributes[:category]
@run_time = attributes[:run_time]
@year = attributes[:year]
@price = attributes[:price]
end
DVD.new 'Second'
DVD.new 'Third', price: 29.99, year: 2011