14

私はルビーの専門家ではないので、これが問題になっています。しかし、Ruby でオブジェクト/クラスの配列を作成するにはどうすればよいでしょうか? どのように初期化/宣言しますか? 助けてくれてありがとう。

これは私のクラスで、その配列を作成したいと思います:

class DVD
  attr_accessor :title, :category, :runTime, :year, :price

  def initialize()
    @title = title
    @category = category
    @runTime = runTime
    @year = year
    @price = price
  end
end
4

3 に答える 3

19

Rubyはダックタイピング(動的型付け)であり、ほとんどすべてがオブジェクトであるため、任意のオブジェクトを配列に追加するだけです。例えば:

[DVD.new, DVD.new]

2枚のDVDを含むアレイを作成します。

a = []
a << DVD.new

DVDをアレイに追加します。配列関数の完全なリストについては、RubyAPIを確認してください。

ところで、DVDクラス内のすべてのDVDインスタンスのリストを保持したい場合は、クラス変数を使用してこれを行い、新しいDVDオブジェクトを作成するときにその配列に追加できます。

class DVD
  @@array = Array.new
  attr_accessor :title, :category, :runTime, :year, :price 

  def self.all_instances
    @@array
  end

  def initialize()
    @title = title
    @category = category
    @runTime = runTime
    @year = year
    @price = price
    @@array << self
  end
end

今あなたがするなら

DVD.new

これまでに作成したすべてのDVDのリストを取得できます。

DVD.all_instances
于 2013-01-26T01:29:14.287 に答える
6

Ruby でオブジェクトの配列を作成するには:

  1. 配列を作成し、名前にバインドします。

    array = []
    
  2. それにオブジェクトを追加します。

    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

引数を取らないにもかかわらず、インスタンス変数を設定します。効果的に起こることは次のとおりです。

  1. attributeリーダーメソッドが呼び出されます
  2. 未設定の変数を読み取ります
  3. 戻るnil
  4. 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
于 2013-01-26T11:21:02.983 に答える