Ruby ancestors Method Tutorial

  • Post author:
  • Post category:Ruby

In this section, we will learn what the ancestors method is and how to use it in Ruby.

What is ancestors method in Ruby?

The Ruby ancestors method is used to get the list of classes and modules and their priorities on top of a class that a program will search first in order to find a method and invoke it.

Note that we call this method on top of a class that we want to create an object from.

Example: using the ancestors method in Ruby

class Human 
    def print_name 
        puts "Hello from Human class" 
    end 
end 
module PrintFullName
    def print_name
        puts first_name, last_name, age, id 
    end 
end 

class Person < Human

    include PrintFullName 

    attr_accessor :first_name, :last_name, :age, :id 

    def initialize (first_name, last_name, age, id)
        self.first_name = first_name
        self.last_name = last_name 
        self.age = age 
        self.id = id 
    end 
end 	

prs = Person.new("John","Doe",100, 43221)

puts Person.ancestors 

Output:

Person

PrintFullName

Human

Object

Kernel

BasicObject

How does ancestors method work in Ruby?

Here in this example, the order of priorities starts from the Person class and then moves to the PrintFullName then Human, Object, Kernel, and then finally BasicObject.

This means when this program runs, first it’s the Person class that will be searched for a method that is invoked from the object that is created from the Person class.

After that, if the Person class didn’t have the specified method, it’s the PrintFullName module to be checked for the method.

Now if this module also didn’t have the target method, then the program will continue its search for the method in the `Human` class, then Object class and so on until the invoked method is found! Otherwise, if none of them had the specified method, an error will return instead.

Leave a Reply