In order to create an array of objects in Ruby:
Create the array and bind it to a name:
array = []
Add your objects to it:
array << DVD.new << DVD.new
You can add any object to an array, at any time.
If you wish to have access to every instance of the DVD
class, then you can rely on ObjectSpace
:
class << DVD
def all
ObjectSpace.each_object(self).entries
end
end
dvds = DVD.all
By the way, the instance variables are not being initialized correctly.
The following method call:
attr_accessor :title, :category, :run_time, :year, :price
Automatically creates attribute
/attribute=
instance methods to get and set the value of the instance variables.
The initialize
method, as defined:
def initialize
@title = title
@category = category
@run_time = run_time
@year = year
@price = price
end
Sets the instance variables, despite taking no arguments. What effectively happens is:
- The
attribute
reader method is called
- It reads the unset variable
- It returns
nil
nil
becomes the value of the variable
What you want to do is pass the values of the variables to the initialize
method:
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
Also, if the only required attribute is the DVD
's title then you can do it this way:
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