It’s code refactoring - all 2D shapes need the method ‘perimeter’.
Instead of implementing the method separately for each shape - and it is
the same for each shape - you put it inside a module an simply add the
module to each shape.
If you ever need to change the ‘perimeter’ method, you need to do so
only once.
Btw, sides.inject(0) { |sum, side| sum + side } can be shortened to
sides.inject(&:+)
If you include the module, all methods are added to the class. So this
code
module Perimeter
def perimeter
sides.inject(0) { |sum, side| sum + side }
end
end
class Rectangle
include Perimeter
end
is the same as this:
class Rectangle
def perimeter
sides.inject(0) { |sum, side| sum + side }
end
end
The only connection between the methods ‘perimeter’ and ‘sides’ are that
they are methods of the same class - and thus they can access all class
variables and all methods of the object.
‘perimeter’ can use the method ‘sides’ because it has been included in
the class Square/Rectangle.