Menu
CoddyTech

模块作为混入

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

Kotlin 接口可以提供默认方法,而委托可以复用实现。Ruby 的 include 会将模块方法加入查找过程,同时保留一个类父类。Kotlin 的冲突解决规则和 Ruby 的祖先顺序有所不同。模块也可以用作命名空间,而包含模块与加载其源文件是两回事。

Kotlin:完整程序

interface Greeting {fun hello()="hello"}
class Host:Greeting

fun main(){
println(Host().hello())
}

Ruby:完整程序

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

挑战

简单

定义一个名为 CostPair 的模块,其中包含返回 cost(n)+cost(n) 的 pair_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自我测试

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

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

自己练习: Ruby 在线编译器