How do you do polymorphism in Ruby?

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

    The principle of duck typing is just that the object has to respond to the called methods. So something like that may do the trick too :

    module Sleeping
      def sleep; puts "#{self} sleeps"
    end
    
    dog = "Dog"
    dog.extend Sleeping
    class << dog
      def make_noise; puts "Woof!" end
    end
    
    class Cat
      include Sleeping
      def to_s; "Cat" end
      def make_noise; puts "Meow!" end
    end
    
    [dog, Cat.new].each do |a|
      a.sleep
      a.make_noise
    end
    

提交回复
热议问题