模块作为命名空间
Coddy 面向 Go 开发者的 Ruby 课程的第 26 课,共 48 课。
Go 包会对编译后的声明进行分组,导入则会在构建过程中加载依赖项,而不是在调用位置评估任意源文件。Ruby 的 require_relative 会在运行时加载文件,而模块会显式地对常量和方法进行分组。文件名不会创建命名空间。Ruby 的 include 会添加实例行为,而不是导入 Go 包。
Go:完整程序
package main
import ("fmt")
func subtotal(price,quantity int)int{return price*quantity}
func main(){
fmt.Println(subtotal(4,3))
}
Ruby:完整程序
module TextTools
def self.shout(text)
text.upcase
end
end
puts TextTools.shout("elm")挑战
简单定义 Shipping.fee(weight):返回 weight 的 2 倍加 3,weight 为 0..100 的整数。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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器