Menu
CoddyTech

作为混入的模块

Coddy 面向 C 开发者的 Ruby 课程的第 34 课,共 48 课。

C 通过回调表直接复用函数,但没有原生的混入声明。Ruby 的 include 会将模块插入实例方法查找链中。这样可以复用行为,而不会添加第二个类超类。include 不是加载文件,而扩展类对象与混入实例方法是不同的操作。

C:完整程序

#include <stdio.h>
static const char *hello(void){return "hello";}
struct Host{const char *(*greet)(void);};

int main(void) {
struct Host host={hello};puts(host.greet());
return 0;
}

Ruby:完整程序

module Tagged
  def tag; "tracked"; end
end
class Parcel
  include Tagged
end
puts Parcel.new.tag
challenge icon

挑战

简单

定义 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)
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 Ruby中的所有课

自己练习: Ruby 在线编译器