How do you do polymorphism in Ruby?

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

    This is how I would write it:

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

    It's not really different from the other solutions, but this is the style that I would prefer.

    That's 12 lines vs. the 41 lines (actually, you can shave off 3 lines by using a collection initializer) from the original C# example. Not bad!

提交回复
热议问题