Ruby: module, require and include Ruby: module, require and include ruby ruby

Ruby: module, require and include


In short: you need to extend instead of include the module.

class MyApp  extend MyModule  self.halloend

include provides instance methods for the class that mixes it in.

extend provides class methods for the class that mixes it in.

Give this a read.


The issue is that you are calling hallo in the class definition, while you add it as an instance method (include).

So you could either use extend (hallo would become a class method):

module MyModule  def hallo    puts "hallo"  endendclass MyApp  extend MyModule  self.halloend

Or either call hallo in an instance of MyApp:

module MyModule  def hallo    puts "hallo"  endendclass MyApp  include MyModuleendan_instance = MyApp.newan_instance.hallo


Your code is working - but including a module does not do what you think it does. The class including the module will not get the methods - the objects from this class will.

So this will work :

class MyApp  include MyModuleendmy_app_object = MyApp.newmy_app_object.hallo # => hallo

my_app_object is an object of class MyApp, which has a mixins of module MyModule. Take a look there for a complete explanation of modules and mixins.