Ruby编程:模块混入与代码块迭代的实用指南
1. 模块作为混入工具
在面向对象编程中,类具有容器和工厂的双重属性,我们可以在类中编写代码并创建实例。同时,Ruby类还可以形成继承树,创建新类时选择父类是关键步骤。
有时候,我们会遇到需要在不相关的类之间共享代码的情况。例如,我们为 Document 类编写了一个 number_of_cliches 方法来统计文档中陈词滥调的数量:
class Document
CLICHES = [ /play fast and loose/,
/make no mistake/,
/does the trick/,
/off and running/,
/my way or the highway/ ]
def number_of_cliches
CLICHES.inject(0) do |count, phrase|
count += 1 if phrase =~ content
count
end
end
# Rest of the class omitted...
end
当公司进入数字市场,引入了 ElectronicBook 类,并且大家希望这个类也能使用 number_of_cliches 方法时,该怎么办呢?一种可能的做法是创建一个公共的超类,但在很
超级会员免费看
订阅专栏 解锁全文
10

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



