Ruby is definitely a loose language. All classes in the language even core classes like the base Object are open and can be modified at any time. Also Ruby in addition to allowing you to do object inheritance allows you to include and extend modules within your Classes.
Open Classes
What open classes means is that you are free to modify and change any class at any time during the execution of your script or application. In addition any changes made will affect existing instances of that class. Lets take a quick look at modifying the main Object class.
class Object
def myMethod
puts "this is my new method on the base Object Class"
end
end
By adding this method to the main Object it now means that every Class that extends from the Base Object e.g. everything now has this function. In essence if my had a myClass object that we already instantiated after the above code runs you would be able to call the myMethod function for it and it would output the text.
Include and Extend Classes with Modules
The include and extend keywords allow you add module functions and constants to the specified class and it’s instances. To start off lets first discuss what a Module is in Ruby.
The Basics of Modules
A Module is similar to a class with the exception that they can have no instances or subclasses. Instead what they are used for is for defining a collection of constants or static methods. For example the Math module in Ruby defines functions for performing basic calculations like square root and constants like Pi. To define a module you simply use the module keyword.
module MyModule
def myMethod
puts "this is my method in my module"
end
end
Including Modules in Classes
You can add methods of a Module to an instance of a class by including it in the class by the include keyword.
class SampleClass
include MyModule
end
Having included our module we will find that the methods defined in the module are now added to the Class and any instances of the Class will be able to call the methods. The methods will not be accessible from the Class itself.
obj = SampleClass.new
obj.myMethod // outputs: this is my method in my module
SampleClass.myMethod // NoMethodError
Extending Modules in Classes
Conversely to Includes, Extending Modules makes the methods available at the class level and not for instances.
class AnotherClass
extend MyModule
end
obj = SampleClass.new
obj.myMethod // NoMethodError
SampleClass.myMethod // outputs: this is my method in my module
Like I said in the beginning Ruby is a very loose language. It allows you at any moment to modify or overwrite Classes, Methods, and Constants of any Object including those objects that are core to the language. However the include and extend functionality allows you to use the mixin technique to implementing multiple inheritance without supporting true multiple inheritance.
Comments & Questions
Add Your Comment