Menu
CoddyTech

将模块作为 Mixin

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

通过 with 添加的 Dart 混入和通过 include 添加的 Ruby 模块都会复用实例行为。它们的类型约束、组合方式和查找规则各不相同;Dart 混入可以声明 on 要求。Ruby 模块也可以用作命名空间,而且不会增加第二个类超类。include 与加载模块文件是两回事。

Dart:完整程序

mixin Greeting {String greet()=>"hello";}
class Host with Greeting {}

void main() {
  print(Host().greet());
}

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自我测试

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

面向 Dart 开发者的 Ruby 课程中的所有课

自己练习: Ruby 在线编译器