×

ruby · level 2 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A adds a module's skills to your class.

A module can also be a mixin. Write include and the module's name inside a class, and every object of that class gets the module's methods. A class can mix in many modules, which lets Ruby share skills without inheritance.

Ruby's mixin needs one method from you: <=>, the . It compares two objects and gives -1 if the first is smaller, 0 if they are equal and 1 if it is bigger. In return you get <, > and between?, and .sort and .max work too.

class Parcel
  include Comparable
  attr_reader :kg
  def initialize(kg)
    @kg = kg
  end
  def <=>(other) = kg <=> other.kg
end
p Parcel.new(3) < Parcel.new(5)
p [Parcel.new(9), Parcel.new(2)].max.kg

Numbers and strings already know <=>, so kg <=> other.kg does the hard work for you.