Menu
CoddyTech

Modules as Mixins

Lesson 34 of 48 in Coddy's Ruby for Java Developers course.

Java interfaces can supply default methods but participate in Java's type and conflict-resolution rules. Ruby modules included in a class supply instance methods through the ancestor chain. The two mechanisms both share behavior but should not be described as identical inheritance systems. Ruby modules can also be namespaces.

Java: complete program

import java.util.*;
public class Main {
  interface Tagged { default String tag() { return "tracked"; } }
  static class Parcel implements Tagged {}

  public static void main(String[] args) {
    System.out.println(new Parcel().tag());
  }
}

Ruby: complete program

module Tagged
  def tag; "tracked"; end
end
class Parcel
  include Tagged
end
puts Parcel.new.tag
challenge icon

Challenge

Easy

Define CostPair module with pair_cost(n) returning cost(n)+cost(n). Flat includes it, has initialize(amount) and cost(n) returning amount. PerUnit includes it, initialized with rate and cost(n) returning rate*n. Input is flat or unit, amount and units; return pair_cost.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, cost_pair.rb, flat.rb, per_unit.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for Java Developers

Practice on your own: Online Ruby compiler