DEV Community

neha-saggam
neha-saggam

Posted on • Updated on

RoR - extend, < (inheritance), include - know the difference

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!
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

I hope this explains the difference between <, extend and include.

Top comments (0)