Ruby中的代码复用:继承、模块与混入
1. 代码的简洁写法
在Ruby中,有更简洁的代码编写方式。Ruby对象有一个名为 method 的方法,它接受一个符号并返回同名的对象方法。我们可以利用符号的 to_proc 特性:
print "(t)imes or (p)lus: "
operator = gets
print "number: "
number = Integer(gets)
method = number.method(operator.start_with?("t") ? :* : :+)
puts((1..10).map(&method).join(", "))
运行示例:
(t)imes or (p)lus: t
number: 2
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
在这个例子中,我们根据输入使用 method 方法获取 :+ 或 :* 方法,并利用 & 的 to_proc 功能创建一个调用该方法的 proc 。
2. 软件设计中的代码复用原则
良好的软件设计原则之一是消除不必要的重复。我们应确保应用中的每个概念在代码中只表达一次
超级会员免费看
订阅专栏 解锁全文
52

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



