reminder : ruby include vs require

Written by Walter on 21/1/2011

< >

Sometimes I mess these up (by switching programming in C++ ruby, python and other languages). Just put this into a post as a quick memory reminder.

In short, require is like include in C/C++

Ruby's include is really handy to inject a module's members into a class (great for writing gems). Finally you can also just extend a class instance with some functionality from a module by using 'extend'. Below is an example that uses these concepts:


$ cat engine.rb 

module Engine
  def start
    puts "vroem vroem"
  end
end


$ cat include_vs_require.rb 
require "./engine.rb"

class Car
  include Engine

  def initialize( name )
    @name = name
  end

  def brand
    @name
  end
end

module BadEngine
  def start
    puts "prutel prutel"
  end
end


puts "The audi class instance uses the engine injected with include"
audi = Car.new("Audi TT")
puts audi.brand
audi.start


puts "The opel class instance uses a different module that is injected solely for this object instance"
opel = Car.new("Opel")
puts opel.brand
opel.extend BadEngine
opel.start

At runtime we see how it all goes works here with ruby requires and includes :


$ ruby include_vs_require.rb 
"The audi class instance uses the engine injected with include"
"Audi TT"
"vroem vroem"
"The opel class instance uses a different module that is injected solely for this object instance"
"X5"
"prutel prutel"

Basically a module is like a c++ namespace equivalent (not really but it serves a similar purpuse not polluting the main scope).

In ruby you can also nest classes and modules inside eachother as much as you like (not possible in C or java ;) ).

Back to archive