继承与重写
Coddy 面向 Luau 开发者的 Ruby 课程的第 32 课,共 48 课。
Luau 的 __index 链可以将缺失的查找委托给另一个表,而 Ruby 则使用包含重写和模块的类-超类链。元表链是一种选择的实现模式,而不是 Ruby 中的类声明。子表自身的字段优先于其备用字段。请验证实际的分发路径,而不是假设它们具有相同的继承规则。
Luau:完整程序
local Base={name=function()return "base" end};local Child=setmetatable({name=function()return "child" end},{__index=Base});print(Child.name())
Ruby:完整程序
class Bird
def sound; "chirp"; end
end
class Owl < Bird
def sound; "hoot"; end
end
puts Bird.new.sound
puts Owl.new.sound挑战
简单定义 Fee#cost(units) 返回 units * 2。DiscountFee 继承自 Fee 并重写 cost,返回 units(所有 units 均为非负数)。solve 读取 base 或 discount 以及随后的 units;构造所选类型的对象。
从 solve(input) 返回文本,无需打印。被锁定的驱动程序代码会打印返回的文本(末尾带有一个换行符),并独立检查所需的公共 API。
你的代码应写在 exercise.rb、fee.rb、discount_fee.rb 中。main.rb 包含提供的输入/输出代码,无法编辑。
亲手试试
require_relative 'exercise'
require_relative 'fee'
require_relative 'discount_fee'
def check(value)
raise 'Public API check failed' unless value
end
check(DiscountFee.new.is_a?(Fee))
check(Fee.new.cost(7) == 14 && DiscountFee.new.cost(7) == 7)
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Luau 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器