模块作为混入
Coddy 面向 Python 开发者的 Ruby 课程的第 34 课,共 48 课。
Python 通常通过基类共享方法。Ruby 模块可以通过包含来提供实例方法,同时保持类的超类不变。include 会影响实例查找;extend 会为特定对象添加方法,通常是类对象。混入可能会调用宿主提供的方法,因此请记录这一要求。模块不能像类那样使用 new 实例化。这个示例添加了一个固定的标记方法,而不是实现所需的成本汇总。
Python:完整程序
class Tagged:
def tag(self):
return "tracked"
class Parcel(Tagged):
pass
print(Parcel().tag())Ruby:完整程序
module Tagged
def tag; "tracked"; end
end
class Parcel
include Tagged
end
puts Parcel.new.tag挑战
简单定义 CostPair 模块,其中的 pair_cost(n) 返回 cost(n)+cost(n)。Flat 包含该模块,并有 initialize(amount) 和返回 amount 的 cost(n)。PerUnit 包含该模块,使用 rate 初始化,且 cost(n) 返回 rate*n。输入包含 flat 或 unit、amount 和 units;返回 pair_cost。
从 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,同时独立检查必需的公共 API。
你的代码写在 exercise.rb、cost_pair.rb、flat.rb 和 per_unit.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。
亲手试试
require_relative 'exercise'
require_relative 'cost_pair'
require_relative 'flat'
require_relative 'per_unit'
def check(value)
raise 'Public API check failed' unless value
end
check(Flat.ancestors.include?(CostPair) && PerUnit.ancestors.include?(CostPair))
check(Flat.new(7).cost(2) == 7 && PerUnit.new(3).cost(2) == 6)
probe = Class.new { include CostPair; def cost(n); n + 4; end }.new
check(probe.pair_cost(3) == 14)
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器