How do you do polymorphism in Ruby?

后端 未结 8 1476
灰色年华
灰色年华 2021-01-01 21:40

In C#, I can do this:

class Program
{
    static void Main(string[] args)
    {
        List animals = new List();

        anima         


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 22:27

    A little variant of manveru's solution which dynamic create different kind of object based in an array of Class types. Not really different, just a little more clear.

    Species = [Dog, Cat]
    
    Species.each do |specie|
      animal = specie.new   # this will create a different specie on each call of new
      print animal.MakeNoise + "\n"
      animal.Sleep
    end
    

提交回复
热议问题