How do you do polymorphism in Ruby?

后端 未结 8 1472
灰色年华
灰色年华 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:25

    Building on the previous answer, is this how you might do it?


    Second cut after clarification:

    class Animal
        def MakeNoise
            raise NotImplementedError # I don't remember the exact error class
        end
        def Sleep
            puts self.class.to_s + " is sleeping."
        end
    end
    
    class Dog < Animal
        def MakeNoise
            return "Woof!"
        end
    end
    
    class Cat < Animal
        def MakeNoise
            return "Meow!"
        end
    end
    
    animals = [Dog.new, Cat.new]
    animals.each {|a|
        puts a.MakeNoise
        a.Sleep
    }
    

    (I'll leave this as is, but "self.class.name" wins over ".to_s")

提交回复
热议问题