Modules and Gems
Modules play two roles in Ruby: organization and mixins
Modules can act like a namespace to keep the different parts of a library organized and spread out across separate files.
# version.rb module DeLorean VERSION = "1.0.0" end
# functions.rb module DeLorean def DeLorean.cool? true end end
# student.rb module DeLorean class Student def hello puts "hi hello" end end end
# delorean.rb require "version" require "functions" require "student"
You can access the whole library with
require "delorean" and the the
DeLorean module is available in the global scope. You access methods with
. and constants with
am_i_cool? method to the
Student class in a separate file that uses the
Module methods can be "mixed in" to a class using
include. The class gets all the instance methods defined in the module.
module Superpowers def fly @flying = true puts "flying away!" end def flying? @flying end def land @flying = false puts "back on the ground" end end class Human end h = Human.new h.fly # NoMethodError: undefined method `fly' for #<Human:0x007fbe2589c390> class Human include Superpowers # ... end h = Human.new h.fly # "flying away!"
- Create a
Humanclass with a
- Create an
Invisiblemodule with methods
- Create a
LaserEyesmodule with the method
- Create another module with your own super power
- Create subclasses of
Humanthat mixin different superpower modules to create different super heroes
Where Node used packages and npm, Ruby uses gems and bundler. Instead of a
package.json, we create and maintain a
Gemfile. Instead of a
node_modules folder, the gems get installed to a global location, but bundler generally takes care of that for us.
Gemfile using at least three gems from https://github.com/markets/awesome-ruby and write a basic Ruby script that uses them.