믹스인으로서의 모듈
Coddy의 Dart 개발자를 위한 Ruby 코스 레슨. 48개 중 34번째.
with로 추가하는 Dart 믹스인과 include로 추가하는 Ruby 모듈은 모두 인스턴스 동작을 재사용합니다. 이들의 타입 제약, 구성 방식, 조회 규칙은 서로 다르며, Dart 믹스인은 on 요구 사항을 선언할 수 있습니다. Ruby 모듈은 네임스페이스로도 사용할 수 있으며 두 번째 클래스 상위 클래스를 추가하지 않습니다. 모듈을 포함하는 것은 모듈 파일을 불러오는 것과 다릅니다.
Dart: 완전한 프로그램
mixin Greeting {String greet()=>"hello";}
class Host with Greeting {}
void main() {
print(Host().greet());
}
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)
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Dart 개발자를 위한 Ruby의 모든 레슨
직접 연습해 보세요: 온라인 Ruby 컴파일러