默认值与关键字
Coddy Ruby for C++ Developers 课程的第 13 课,共 48 课。
C++ 提供默认参数和重载,但没有普通的命名调用语法。Ruby 提供位置参数默认值和关键字参数。Ruby 3 将位置哈希与关键字分开,因此转发关键字时要使用双星号展开。重复定义 Ruby 方法不会创建根据静态参数类型选择的 C++ 重载集。
C++:完整程序
#include <iostream>
#include <string>
std::string greet(std::string name="guest"){return name;}
int main() {
std::cout<<greet()<<":"<<greet("Ada")<<"\n";
}
Ruby:完整程序
def border(text, mark: ".")
mark + text + mark
end
puts border("x")
puts border("x", mark: "!")挑战
简单定义 charge(units, rate: 4, discount: 0),使其返回 units*rate-discount。输入可以只有 units、包含 units rate,或包含 units rate discount。对于省略的字段,solve 必须使用默认值。
让 solve(input) 返回文本,不要打印。锁定的驱动程序会用一个末尾换行符打印返回的文本,并独立检查必需的公共 API。
你的代码写在 exercise.rb、pricing.rb 中。main.rb 保存了提供的输入/输出代码,不能编辑。
亲手试试
require_relative 'exercise'
require_relative 'pricing'
def check(value)
raise 'Public API check failed' unless value
end
check(charge(7) == 28)
check(charge(7, discount: 3) == 25)
check(charge(2, rate: 9, discount: 1) == 17)
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Ruby for C++ Developers中的所有课
自己练习: Ruby 在线编译器