如何将对象添加到数组?红宝石

时间:2011-10-20 13:02:53

标签: ruby arrays object

如何用猫狗随机填充动物名单数组?

class Dog
  def speak
    puts "woof"
  end
end

class Cat
  def
    puts "meow"
  end
end

class PetLover
  def random_animal     
  end

  Animallist = Array.new(9)
  #Animallist[]
end

1 个答案:

答案 0 :(得分:2)

我认为以下内容将对您提供一些帮助:

class Dog
  def speak
    puts "woof"
  end
end

class Cat
  def speak
    puts "meow"
  end
end

class PetLover
  attr_accessor :species
  def initialize
    @species = [Dog, Cat]
  end

  def random_animal  
    @species[rand(@species.size)].new
  end

  def animals(n)
    ary = []
    n.times do 
      ary << random_animal
    end
    ary
  end
end

pl = PetLover.new
p pl.animals(10)