为了在Ruby中创建对象数组:
Create the array and bind it to a name:
array = []
Add your objects to it:
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
/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)
@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
@@movies = Array DVD.new
但很快发现那行不通。 - Chris Cruz