2011-10-20 47 views
-6

我如何随猫和狗随机填写动物列表数组?如何将对象添加到数组?红宝石

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 
+3

你的问题不显示了很多的努力...你问尝试过什么呢? – Mischa

回答

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) 
+0

如果您使用1.9'random_animal',可以简化为'@sys.sample.new'。 –

+0

当然。但由于看起来作者还在学习,我认为这个定义更具说教性。 – p4010