Инструкции
Создайте класс Box, который:
- Имеет атрибут
volume(устанавливается в initialize) - Включает модуль
Comparable - Реализует оператор
<=>(spaceship) для сравнения по объёму
Это даст вам <, >, ==, <=, >= бесплатно!
Подсказки:
- Включите Comparable
- Реализуйте def <=>(other)
- Верните volume <=> other.volume
Ваш код
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
Результаты
Нажмите "Запустить тесты", чтобы увидеть результаты