믹스인으로서의 모듈
Coddy의 R 개발자를 위한 Ruby 코스 레슨. 48개 중 34번째.
R에서는 Ruby의 모듈 include와 달리 환경과 제네릭 메서드를 통해 함수를 공유하거나 위임하는 경우가 많습니다. Ruby의 include는 인스턴스 메서드를 조상 체인에 삽입하면서 하나의 클래스 슈퍼클래스를 유지합니다. Extend는 개별 객체에 메서드를 추가합니다. 믹스인은 호스트 메서드를 요구할 수 있으므로, 이러한 전제 조건을 문서화하세요. 모듈은 별도로 네임스페이스 역할을 할 수도 있습니다.
R: 완전한 프로그램
hello <- function() "hello";host <- list(hello=hello);cat(host$hello(),"\n",sep="")
Ruby: 완전한 프로그램
module Tagged
def tag; "tracked"; end
end
class Parcel
include Tagged
end
puts Parcel.new.tag챌린지
쉬움pair_cost(n)이 cost(n)+cost(n)을 반환하는 CostPair 모듈을 정의하세요. Flat은 이 모듈을 포함하고, initialize(amount)와 amount를 반환하는 cost(n)을 가집니다. PerUnit은 이 모듈을 포함하고, rate로 초기화되며 rate*n을 반환하는 cost(n)을 가집니다. 입력은 flat 또는 unit, amount와 units로 구성됩니다. pair_cost를 반환하세요.
출력하지 말고 solve(input)에서 텍스트를 반환하세요. 잠긴 드라이버는 반환된 텍스트를 끝에 줄바꿈 하나를 붙여 출력하며, 필수 공개 API를 별도로 확인합니다.
코드는 exercise.rb, cost_pair.rb, flat.rb, per_unit.rb에 작성하세요. main.rb에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
require_relative 'exercise'
require_relative 'cost_pair'
require_relative 'flat'
require_relative 'per_unit'
def check(value)
raise 'Public API check failed' unless value
end
check(Flat.ancestors.include?(CostPair) && PerUnit.ancestors.include?(CostPair))
check(Flat.new(7).cost(2) == 7 && PerUnit.new(3).cost(2) == 6)
probe = Class.new { include CostPair; def cost(n); n + 4; end }.new
check(probe.pair_cost(3) == 14)
puts solve(STDIN.read)
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
R 개발자를 위한 Ruby의 모든 레슨
직접 연습해 보세요: 온라인 Ruby 컴파일러