ruby include vs require

Written by Walter

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 ;).


wschrep@emd-walter-thinkpad:~/railsWork$ cat engine.rb

module Engine
def start
p "vroem vroem"
end
end


wschrep@emd-walter-thinkpad:~/railsWork$ 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
p "prutel prutel"
end
end


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


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


So require is like include in C/C++
Then 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'

At runtime we see how it all goes down with ruby :

wschrep@emd-walter-thinkpad:~/railsWork$ 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