ruby · level 2 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Spaceships everywhere. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
p 3 <=> 7
p "b" <=> "a"
p 4 <=> 4
your turn
Your turn. Find the fastest lap.
Fill in three lap times in seconds, then press run. .min uses your <=> to find the fastest.
fix it
Comparable is mixed in, but nothing compares. Fix it!
- Read the error. Ruby could not compare two boxes. Which method does Comparable need from you?
- Comparable only looks for a method called
<=>, the spaceship operator. - Rename compare to <=> on line 7, then press run.
nailed it
your objects can stand in line now. :D
includemixes a module's methods into a class.- Comparable needs one method from you:
<=>. <=>gives -1, 0 or 1.
new words in your collection
- mixin
- Comparable
- spaceship operator
This lesson isn’t saved. A free account remembers every lesson you finish.