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?
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: