RubyMonk clarification

Would someone please clarified this solution:

module Perimeter
def perimeter
sides.inject(0) { |sum, side| sum + side }
end
end

class Rectangle
include Perimeter

def initialize(length, breadth)
@length = length
@breadth = breadth
end

def sides
[@length, @breadth, @length, @breadth]
end
end

class Square
include Perimeter

def initialize(side)
@side = side
end

def sides
[@side, @side, @side, @side]
end
end

I don’t understand point of module Perimeter

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(&:+)

I don’t understand def sides in class Rectangle class Square.

what does def sides have to do with def perimeter?I don’t understand
the connection

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.

sides.inject(0) { |sum, side| sum + side }

is short for

sides().inject(0) { |sum, side| sum + side }

  1. method sides gets called with no arguments, returning an array
  2. method inject of the array gets called, passing the number ‘0’ and
    the block ‘{|sum,side|sum+side}’ as arguments.
  3. the block gets called, by method inject, once for each element of the
    array, adding its value to the sum

I’m confused with sides in def perimeter with def sides.

def sides in classes Square/Rectangle is method so when sides.injection
in def perimeter it calls method def sides with an array as argument

Am i right?

Just to be sure:

sides in sides.inject is def sides from class Square/Rectangle

thanks for the rest of explanation

Yes, it is method sides from Square/Rectangle (there is no other one).

By including the module, you add the method perimeter to the
Square/Rectangle class.