How do you do polymorphism in Ruby?

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

    All the answers so far look pretty good to me. I thought I'd just mention that the whole inheritance thing is not entirely necessary. Excluding the "sleep" behaviour for a moment, we can achieve the whole desired outcome using duck-typing and omitting the need to create an Animal base class at all. Googling for "duck-typing" should yield any number of explanations, so for here let's just say "if it walks like a duck and quacks like a duck..."

    The "sleep" behaviour could be provided by using a mixin module, like Array, Hash and other Ruby built-in classes inclue Enumerable. I'm not suggesting it's necessarily better, just a different and perhaps more idiomatically Ruby way of doing it.

    module Animal
      def sleep
        puts self.class.name + " sleeps"
      end
    end
    
    class Dog
      include Animal
      def make_noise
        puts "Woof"
      end
    end
    
    class Cat
      include Animal
      def make_noise
        puts "Meow"
      end
    end
    

    You know the rest...

提交回复
热议问题