# Modules in Ruby

DevFeed: [Modules in Ruby](<https://devfeed.tech/articles/modules-in-ruby-21031.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2015/07/05/composition-in-ruby/>)

Published: 2015-07-05T12:00:00Z

Content type: tutorial

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Ruby](<https://devfeed.tech/topics/ruby.md>), [Code](<https://devfeed.tech/topics/code.md>)

Tags: [module](<https://devfeed.tech/tags/module.md>), [modules](<https://devfeed.tech/tags/modules.md>), [patterns](<https://devfeed.tech/tags/patterns.md>), [ruby](<https://devfeed.tech/tags/ruby.md>)

## AI overview

An introduction to Ruby modules for sharing functionality between classes. It explains the difference between extending and including a module, then shows how self.included and an inner ClassMethods module can combine class methods and instance methods in one organized module.

## Source excerpt

Currently, one hundred percent of Year of Commits' commits have been to Ruby repositories. Ruby has many strengths and is a very malleable language. Ruby can be written functionally or object oriented. I tend to lean toward the latter and find myself using a few different patterns regularly. One powerful tool Ruby provides is the use of Modules. Modules When code is to be shared between classes, a Module is created to encapsulate the shared functionality. A very simple module looks something like this: module Ripe def ripe? puts "this is ripe!" end end extend With the Ripe module, there are two ways to include its methods in a class. We can extend the module, which makes the method ripe? a class method on the Banana class: class Banana extend Ripe end Banana.ripe? # => this is ripe! include Alternatively, we can include the module, making ripe? an instance method: class Banana include Ripe end banana = Banana.new banana.ripe? # => this is ripe! That's great right? Right! We have methods on methods on methods. As long as we can make modules for our instance and class methods separately, we will be golden. But, what about all the times that we need to define both class and instance methods in one module? Surely it would be crazy to have RipeClassMethods and RipeInstanceMethods right? That looks like amateur hour. There must be a better way. def self.included A very helpful method for dealing with included modules is the included class method. This method is built in Ruby and any class has access to it. By using the included method, it is possible to mix class and instance methods within a single module. When using self.included, we are able to determine which methods are accessible on the instance and on the class. We will use a new inner module named ClassMethods to encapsulate our desired class methods. In our example below, the single parameter base is the class in which the Ripe module is included. module Ripe def self.included(base) # Just like in normal module e