How do you do polymorphism in Ruby?

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

    edit: added more code for your updated question

    disclaimer: I haven't used Ruby in a year or so, and don't have it installed on this machine, so the syntax might be entirely wrong. But the concepts are correct.


    The exact same way, with classes and overridden methods:

    class Animal
        def MakeNoise
            return ""
        end
        def Sleep
            print self.class.name + " is sleeping.\n"
        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|
        print a.MakeNoise + "\n"
        a.Sleep
    }
    

提交回复
热议问题