Modules

View saved

Define a module

Modules namespace methods and can be mixed into classes.

module Greetings
  def hello(name)
    "Hello, #{name}"
  end
end

Include in a class

Included methods become instance methods.

class Person
  include Greetings
end

puts Person.new.hello("Ruby")

Namespaces

Modules also prevent name collisions for classes.

module FreeCourses
  class Lesson
  end
end

lesson = FreeCourses::Lesson.new

Module habits

  • Use modules for shared behavior without inheritance
  • extend adds module methods as class methods
  • Keep modules focused
  • Avoid entangling modules and deep ancestry

Comments

One comment per signed-in account. Comments are saved with this page’s URL.