使用 super 扩展
Coddy Ruby for C++ Developers 课程的第 33 课,共 48 课。
在扩展结果时,C++ 会显式限定基类实现,例如 Tool::features()。Ruby 的 super 会继续查找方法;不带括号的 super 会转发当前参数,而 super() 不传递任何参数。调用可能会在查找链中遇到已包含的模块。请保留该方法是扩展还是替换继承行为这一点。
C++:完整程序
#include <iostream>
#include <string>
struct Tool {virtual std::string features()const{return "read";}virtual ~Tool()=default;};
struct Editor:Tool {std::string features()const override{return Tool::features()+",write";}};
int main() {
Editor editor;std::cout<<editor.features()<<"\n";
}
Ruby:完整程序
class Tool
def features; ["read"]; end
end
class Editor < Tool
def features; super + ["write"]; end
end
puts Editor.new.features.join(",")挑战
简单定义 BaseLabel,使用 text 初始化,并让 render 返回该 text。FramedLabel 继承 BaseLabel,接收 text 和 mark,使用父类进行初始化,并返回 mark+parent_render+mark。solve 的输入包含 text 和一个单字符 mark。
从 solve(input) 返回 text,不要打印。锁定的驱动程序会打印返回的 text,并在末尾添加一个换行符,还会独立检查必需的公共 API。
你的代码应写在 exercise.rb、base_label.rb 和 framed_label.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。
亲手试试
require_relative 'exercise'
require_relative 'base_label'
require_relative 'framed_label'
def check(value)
raise 'Public API check failed' unless value
end
check(BaseLabel.new("raw").render == "raw")
check(FramedLabel.new("branch", "!").render == "!branch!")
check(FramedLabel.new("x", "?").is_a?(BaseLabel))
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Ruby for C++ Developers中的所有课
自己练习: Ruby 在线编译器