How do you do polymorphism in Ruby?

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

    Using idiomatic Ruby

    class Animal
      def sleep
        puts "#{self.class} is sleeping"
      end
    end
    
    class Dog < Animal
      def make_noise
        "Woof!"
      end
    end
    
    class Cat < Animal
      def make_noise
        "Meow!"
      end
    end
    
    [Dog, Cat].each do |clazz|
      animal = clazz.new
      puts animal.make_noise
      animal.sleep
    end
    

提交回复
热议问题