继承与重写
Coddy 面向 C 开发者的 Ruby 课程的第 32 课,共 48 课。
C 可以通过函数指针和状态记录实现分派,但没有内置的类继承机制。Ruby 子类会继承一个超类,并且可以重写方法;模块则可以添加可重复使用的行为。对对象的调用会沿着它的方法查找链进行解析。不要以为嵌入一个 C 结构体就会自动创建这条链。
C:完整程序
#include <stdio.h>
struct Bird {const char *(*sound)(void);};
static const char *chirp(void){return "chirp";}
static const char *hoot(void){return "hoot";}
int main(void) {
struct Bird bird={chirp},owl={hoot};puts(bird.sound());puts(owl.sound());
return 0;
}
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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器