Mixin으로서의 모듈
Coddy의 PHP 개발자를 위한 Ruby 코스 레슨. 48개 중 34번째.
PHP 트레이트와 Ruby 모듈은 모두 클래스 간에 동작을 공유하지만, 구성 방식과 조회 규칙은 다릅니다. PHP에는 트레이트 충돌을 해결하는 명시적 구문이 있습니다. Ruby에서 include는 모듈을 조상 체인에 추가하며, 이후 조회에서는 super를 사용할 수 있습니다. Ruby 모듈은 네임스페이스로도 사용할 수 있으며, 인스턴스화할 수 있는 클래스는 아닙니다.
PHP: 완전한 프로그램
<?php
trait Tagged { public function tag() { return "tracked"; } }
class Parcel { use Tagged; }
echo (new Parcel())->tag(), "\n";Ruby: 완전한 프로그램
module Tagged
def tag; "tracked"; end
end
class Parcel
include Tagged
end
puts Parcel.new.tag챌린지
쉬움CostPair 모듈을 정의하고, pair_cost(n)이 cost(n)+cost(n)을 반환하도록 하세요. 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)
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
PHP 개발자를 위한 Ruby의 모든 레슨
직접 연습해 보세요: 온라인 Ruby 컴파일러