FlySwat FlySwat - 6 months ago 28
Ruby Question

How do you do polymorphism in Ruby?

In C#, I can do this:

class Program
{
static void Main(string[] args)
{
List<Animal> animals = new List<Animal>();

animals.Add(new Dog());
animals.Add(new Cat());

foreach (Animal a in animals)
{
Console.WriteLine(a.MakeNoise());
a.Sleep();
}
}
}

public class Animal
{
public virtual string MakeNoise() { return String.Empty; }
public void Sleep()
{
Console.Writeline(this.GetType().ToString() + " is sleeping.");
}
}

public class Dog : Animal
{
public override string MakeNoise()
{
return "Woof!";
}
}

public class Cat : Animal
{
public override string MakeNoise()
{
return "Meow!";
}
}


Obviously, the output is (Slightly paraphrased):


  • Woof

  • Dog is Sleeping

  • Meow

  • Cat is Sleeping



Since C# is often mocked for its verbose type syntax, how do you handle polymorphism/virtual methods in a duck typed language such as Ruby?

Answer

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
}