模块作为命名空间
Coddy 面向 Luau 开发者的 Ruby 课程的第 26 课,共 48 课。
Luau 模块通常通过宿主提供的 require 操作返回表;Coddy CLI 支持相对模块路径。Ruby 的 require_relative 用于加载同级目录下的文件,而声明的模块则用于组织常量和方法。文件名不会自动建立 Ruby 命名空间。Include 用于提供实例行为,而不是加载模块表。
Luau:完整程序
local Helpers={};function Helpers.twice(n)return n*2 end;print(Helpers.twice(4))
Ruby:完整程序
module TextTools
def self.shout(text)
text.upcase
end
end
puts TextTools.shout("elm")挑战
简单定义 Shipping.fee(weight):对于整数重量 0..100,费用为 weight 的 2 倍加上 3。solve 返回该费用。
从 solve(input) 返回文本,无需打印。被锁定的驱动程序会打印返回的文本并在末尾加上一个换行符,并独立检查所需的公共 API。
你的代码写在 exercise.rb 和 shipping.rb 中。main.rb 包含提供的输入/输出代码,无法编辑。
亲手试试
require_relative 'exercise'
require_relative 'shipping'
def check(value)
raise 'Public API check failed' unless value
end
check(Shipping.fee(11) == 25)
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Luau 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器