默认值与关键字
Coddy 面向 C 开发者的 Ruby 课程的第 13 课,共 48 课。
标准 C 没有默认参数或关键字参数;包装函数和选项结构体可以表达类似的约定。Ruby 直接提供位置参数默认值和关键字参数。Ruby 3 区分位置哈希和关键字参数,因此转发关键字参数时要使用显式的双星号展开。保留选项值中“缺失”和“零”的区别。
C:完整程序
#include <stdbool.h>
#include <stdio.h>
struct Options { bool has_repetitions; int repetitions; };
static int repetitions(struct Options options) {
return options.has_repetitions ? options.repetitions : 2;
}
int main(void) {
struct Options missing = {false, 0};
struct Options zero = {true, 0};
printf("%d:%d\n", repetitions(missing), repetitions(zero));
return 0;
}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)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器