0
0
RubyHow-ToBeginner · 3 min read

How to Use Inheritance in Ruby: Syntax and Examples

In Ruby, you use class ChildClass < ParentClass to create inheritance, where ChildClass gets all methods and properties of ParentClass. This lets you reuse code and extend functionality easily.
📐

Syntax

Inheritance in Ruby is done by defining a class that inherits from another class using the < symbol. The child class automatically gets all methods and variables from the parent class.

  • ParentClass: The class you want to inherit from.
  • ChildClass: The new class that inherits from the parent.
ruby
class ParentClass
  def greet
    "Hello from Parent"
  end
end

class ChildClass < ParentClass
end
💻

Example

This example shows a parent class Animal with a method sound. The child class Dog inherits from Animal and can use the sound method without redefining it.

ruby
class Animal
  def sound
    "Some sound"
  end
end

class Dog < Animal
end

dog = Dog.new
puts dog.sound
Output
Some sound
⚠️

Common Pitfalls

One common mistake is forgetting to use the < symbol, which means no inheritance happens. Another is overriding methods in the child class without calling super if you want to keep the parent's behavior.

Also, Ruby does not support multiple inheritance directly, so trying to inherit from more than one class will cause errors.

ruby
class Parent
  def greet
    "Hello from Parent"
  end
end

# Wrong: no inheritance
class Child
  def greet
    "Hello from Child"
  end
end

# Right: inheritance with super
class ChildCorrect < Parent
  def greet
    super + " and Child"
  end
end

begin
  puts Child.new.greet
rescue
  puts "Error: no inheritance"
end
puts ChildCorrect.new.greet
Output
Error: no inheritance Hello from Parent and Child
📊

Quick Reference

  • Use class Child < Parent to inherit.
  • Child class gets all parent's methods and variables.
  • Override methods in child with def method; super; end to keep parent behavior.
  • Ruby does not support multiple inheritance.

Key Takeaways

Use class Child < Parent to create inheritance in Ruby.
Child classes automatically have access to parent class methods and variables.
Override methods in child classes and call super to include parent behavior.
Ruby does not allow multiple inheritance from more than one class.
Inheritance helps reuse code and organize related classes efficiently.