A Ruby class is very similar to the other programming languages class structures. They allow for code to be created within a single object that can be reused etc, the code can have its own separate block of variables/methods for that instance of the required task. It is able to be inherited and extended which is different to a module which only allows for the created module to have methods and constant variables.
module SillyModule # module is a single instance object, e.g. they can have methods and constants def hello "Hello." end end class SillyClass # a class can include a module and expand on it, an class can generate many instances (objects) of itself. include SillyModule # also use the sillymodule as well. def bob "timing is everything." end end s = SillyClass.new puts s.hello # Hello. puts s.class # SillyClass - displays the class name puts s.bob # timing is everything
Save this code as class_module.rb, it will create a module that is included within the SillyClass. To demonstrate that the module is a single instance of a object, if you try to create a new object, e.g. mod = SillyModule.new, the compile will class.rb:20: undefined method `new’ for SillyModule:Module (NoMethodError) since the new method is not part of a module but only a class.