↖️ Show all posts

Use Modules to boost your OOP

There are two ways of using modules, you can either extend or include them in a class.

module Speed
  def accelerate
    puts "I am faster now"

class Car
  include Speed

car1 = Car.new
car1.accelerate # => I am faster now
Car.accelerate # NoMethodError: undefined method `accelerate' for Car:Class

class Ebike
  extend Speed

bike1 = Ebike.new
bike1.accelerate # NoMethodError: undefined method `accelerate' for Object
Ebike.accelerate # => I am faster now

include makes the module’s method instance methods, while extend really is extending your class with its methods.

⬅️ Read previous Read next ➡️