Ruby 编程:继承、模块与文件管理
1. 解决方法歧义
在 Ruby 中,当一个类混入多个模块,而这些模块中存在同名方法时,就会产生方法歧义问题。例如:
module Nice
def salute
puts “Nice to meet you.”
end
end
module Military
def salute
print “To show my respect, I’m hitting my forehead “
puts “with the side of my index finger.”
end
end
class Person
include Nice
include Military
end
p = Person.new
当调用 p.salute 时,会输出军事敬礼的内容。这是因为 Military 模块在 Nice 模块之后被混入,所以 Military 模块中的 salute 方法覆盖了 Nice 模块中的同名方法。
为避免这种歧义带来的调试困难,在编写模块时,应确保模块中的方法名具有独特性,以降低与其他可能混入的模块产生方法名冲突的可能性。
2. 继承与模块的概念
- 继承 :是一种标准的面向对象编程技术,允许我们逐步编程。它能帮助我们在类
超级会员免费看
订阅专栏 解锁全文
447

被折叠的 条评论
为什么被折叠?



