Ruby:对象/类的数组

Chr*_*ruz 12 ruby arrays object

我不是红宝石专家,这给了我麻烦.但是我将如何在ruby中创建一个对象/类数组呢?如何初始化/声明它?在此先感谢您的帮助.

这是我的类,我想创建一个数组:

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

  def initialize()
    @title = title
    @category = category
    @runTime = runTime
    @year = year
    @price = price
  end
end
Run Code Online (Sandbox Code Playgroud)

rik*_*len 19

Ruby是鸭子类型(动态类型)几乎所有东西都是一个对象,所以你可以只添加任何对象到一个数组.例如:

[DVD.new, DVD.new]
Run Code Online (Sandbox Code Playgroud)

将创建一个包含2张DVD的阵列.

a = []
a << DVD.new
Run Code Online (Sandbox Code Playgroud)

将DVD添加到阵列.检查Ruby API以获取完整的数组函数列表.

顺便说一下,如果要保留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
Run Code Online (Sandbox Code Playgroud)

现在,如果你这样做

DVD.new
Run Code Online (Sandbox Code Playgroud)

你可以获得你目前创建的所有DVD的列表:

DVD.all_instances
Run Code Online (Sandbox Code Playgroud)

  • nope,块不是对象:)和,关于类实例变量的真实... (3认同)

Fan*_*nda 6

two_DVD = Array.new(2){DVD.new}

  • 我第一次尝试这样做:Array.new(2,DVD.new),最终创建了同一对象的2个副本。然后我找到了答案“ Array.new(2){DVD.new}”,并找到了它来创建2个唯一的对象,这正是我所需要的。谢谢! (2认同)

Mat*_*ira 5

为了在Ruby中创建一个对象数组:

  1. 创建数组并将其绑定到名称:

    array = []
    
    Run Code Online (Sandbox Code Playgroud)
  2. 添加对象:

    array << DVD.new << DVD.new
    
    Run Code Online (Sandbox Code Playgroud)

您可以随时将任何对象添加到数组中.

如果您希望能够访问DVD该类的每个实例,那么您可以依赖ObjectSpace:

class << DVD
  def all
    ObjectSpace.each_object(self).entries
  end
end

dvds = DVD.all
Run Code Online (Sandbox Code Playgroud)

顺便说一下,实例变量没有正确初始化.

以下方法调用:

attr_accessor :title, :category, :run_time, :year, :price
Run Code Online (Sandbox Code Playgroud)

自动创建attribute/ attribute=实例方法以获取和设置实例变量的值.

initialize方法定义如下:

def initialize
  @title = title
  @category = category
  @run_time = run_time
  @year = year
  @price = price
end
Run Code Online (Sandbox Code Playgroud)

尽管没有参数,但设置实例变量.实际发生的是:

  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
Run Code Online (Sandbox Code Playgroud)

此外,如果唯一需要的属性是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
Run Code Online (Sandbox Code Playgroud)