Menu
CoddyTech

模块作为 Mixin

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

Luau 可以在表之间共享函数或通过元表进行委托,但它没有 Ruby 的模块包含声明。Ruby 的 include 会在保留单一类超类的同时,将实例方法添加到祖先链中。Extend 则是将方法添加到特定的对象中。加载文件、复制函数和包含模块是不同的操作。

Luau:完整程序

local function hello()return "hello" end;local host={hello=hello};print(host.hello())

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) 方法,其 cost(n) 返回 amount。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自我测试

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

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

自己练习: Ruby 在线编译器