模块作为命名空间
Coddy 面向 C# 开发者的 Ruby 课程的第 26 课,共 48 课。
C# 命名空间和 using 指令会解析编译后代码中的名称;使用命名空间不会执行源文件。Ruby 模块会在运行时组织常量和方法,require_relative 会加载相邻文件。Ruby 文件名不会自动创建命名空间。Ruby 的 include 会将行为加入方法查找,而不是用作命名空间导入。
C#:完整程序
using System;
using System.Collections.Generic;
using System.Linq;
Console.WriteLine(TextTools.Words.Shout("elm"));
namespace TextTools {static class Words {public static string Shout(string text)=>text.ToUpperInvariant();}}
Ruby:完整程序
module TextTools
def self.shout(text)
text.upcase
end
end
puts TextTools.shout("elm")挑战
简单定义 Shipping.fee(weight):体重乘以 2 再加 3,整数体重范围为 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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器