Instructions
Create a Box class that:
- Has a
volumeattribute (set in initialize) - Includes the
Comparablemodule - Implements the
<=>(spaceship) operator to compare by volume
This will give you <, >, ==, <=, >= for free!
Hints:
- Include Comparable
- Implement def <=>(other)
- Return volume <=> other.volume
Your Code
class Box
include Comparable
attr_reader :volume
def initialize(volume)
@volume = volume
end
def <=>(other)
volume <=> other.volume
end
end
RSpec.describe Box do
let(:small) { Box.new(10) }
let(:medium) { Box.new(20) }
let(:large) { Box.new(30) }
it "compares with <" do
expect(small < medium).to be true
end
it "compares with >" do
expect(large > medium).to be true
end
it "compares with ==" do
expect(Box.new(10) == Box.new(10)).to be true
end
it "can be sorted" do
boxes = [large, small, medium]
expect(boxes.sort.map(&:volume)).to eq([10, 20, 30])
end
end
Results
Click "Run Tests" to see results