Menu
CoddyTech

用 super 扩展

Coddy 面向 Python 开发者的 Ruby 课程的第 33 课,共 48 课。

Python 的 super 会遵循其方法解析顺序。Ruby 的 super 会调用查找链中下一个匹配的方法,这可能涉及被包含的模块以及父类。不带参数的 super 会转发当前参数;带空括号的 super 不会转发任何参数,显式传入的参数则决定要传递哪些内容。使用它可以扩展现有行为,而不必重复父类的实现。这个示例扩展的是功能列表,而不是输出文本的格式。

Python:完整程序

class Tool:
    def features(self):
        return ["read"]
class Editor(Tool):
    def features(self):
        return super().features() + ["write"]
print(",".join(Editor().features()))

Ruby:完整程序

class Tool
  def features; ["read"]; end
end
class Editor < Tool
  def features; super + ["write"]; end
end
puts Editor.new.features.join(",")
challenge icon

挑战

简单

定义用 text 初始化的 BaseLabel,其 render 方法返回该文本。FramedLabel 继承 BaseLabel,接收 text 和 mark,使用父类初始化,并返回 mark+parent_render+mark。solve 的输入包含 text 和一个单字符 mark。

让 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,同时独立检查必需的公共 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)
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Python 开发者的 Ruby中的所有课

自己练习: Ruby 在线编译器