While going through RoR code I saw extend, includes and <
. Now for any newbie it is difficult to understand the differences between these. Hence let us understand with a few examples,
<
Is used for inheritance
For example,
class Parent
def some_method
puts "Hello from Parent!"
end
end
class Child < Parent
end
my_obj = Child.new
my_obj.some_method #Output: Hello from Parent!
In the above example we see that the class Child is able to use some_method defined in the Parent class i.e it inherits the behavior of a parent. This maintains an "is_a" relationship.
Now a child can override a parent's behavior and instead have its own behavior,
class Parent
def some_method
puts "Hello from Parent!"
end
end
class Child < Parent
def some_method
puts "Hello from Child!"
end
end
my_obj = Child.new
my_obj.some_method #Output: Hello from Child!
extend
This keyword gives you the ability to use the class level or module level methods.
module SomeModule
def some_method
puts "Hello from SomeClass!"
end
end
class Child
extend SomeModule
end
Child.some_method #Output: Hello from SomeClass!
include
include allows you to mix other class functionalities into the included class without having an "is_a" relationship.
class SomeClass
def some_method
puts "Hello from SomeClass!"
end
end
class Main
include SomeClass
end
my_obj = Main.new
my_obj.some_method #Output: Hello from SomeClass!
You are still able to override the method in the main class,
class SomeClass
def some_method
puts "Hello from SomeClass!"
end
end
class Main
include SomeClass
def some_method
puts "Hello from Main!"
end
end
my_obj = Main.new
my_obj.some_method #Output: Hello from Main!
I hope this explains the difference between <, extend and include.
Top comments (0)