How do you do polymorphism in Ruby?(如何在 Ruby 中实现多态性?)
问题描述
在 C# 中,我可以这样做:
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):
- 汪汪
- 狗在睡觉
- 喵喵
- 猫在睡觉
由于 C# 经常因其冗长的类型语法而受到嘲笑,您如何处理 Ruby 等鸭子类型语言中的多态性/虚拟方法?
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
免责声明:我已经一年左右没有使用过 Ruby,也没有在这台机器上安装它,所以语法可能完全错误.但概念是正确的.
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.
"
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 + "
"
a.Sleep
}
这篇关于如何在 Ruby 中实现多态性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Ruby 中实现多态性?


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01