Menu
CoddyTech

super로 확장하기

Coddy의 Python 개발자를 위한 Ruby 코스 레슨. 48개 중 33번째.

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

챌린지

쉬움

텍스트로 초기화되는 BaseLabel을 정의하고, render는 해당 텍스트를 반환하도록 하세요. FramedLabel은 BaseLabel을 상속하고 text와 mark를 받으며, 부모 초기화를 사용하고 mark+parent_render+mark를 반환합니다. solve 입력에는 텍스트와 한 글자의 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 컴파일러