모듈을 믹스인으로 활용하기
Coddy의 Go 개발자를 위한 Ruby 코스 레슨. 48개 중 34번째.
Go의 임베딩과 위임은 Ruby의 모듈 포함 방식을 사용하지 않고 메서드를 재사용합니다. Ruby의 include는 인스턴스 메서드 조회에 모듈을 추가하면서 클래스의 상위 클래스는 하나로 유지합니다. Extend는 특정 객체에 메서드를 추가합니다. 믹스인은 호스트가 제공하는 메서드에 의존할 수 있으므로, 그 계약을 문서화하세요. 모듈 파일을 불러오는 것은 별도의 단계입니다.
Go: 완전한 프로그램
package main
import ("fmt")
type Greeting struct{}
func(Greeting)Hello()string{return "hello"}
type Host struct{Greeting}
func main(){
h:=Host{};fmt.Println(h.Hello())
}
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)
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Go 개발자를 위한 Ruby의 모든 레슨
직접 연습해 보세요: 온라인 Ruby 컴파일러