2011-10-20 51 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