๐ŸŽ“ A1Learner
๐Ÿ”
0 of 34 lessons completed

Ruby Method Lookup

Every method call follows a fixed search order through the classes above the object. This lesson reads that order directly with ancestors and owner.

The ancestors chain

Dog sits first in its own chain, and Animal comes next. The printed array holds names only.

class Animal
  def greet
    puts "hello from Animal"
  end
end
class Dog < Animal
end
p Dog.ancestors

A module sits in the chain

Walker is mixed into Dog, so Walker appears between Dog and Animal. Both walk and greet answer on the dog.

module Walker
  def walk
    puts "walks along"
  end
end
class Animal
  def greet
    puts "hello from Animal"
  end
end
class Dog < Animal
  include Walker
end
p Dog.ancestors
dog = Dog.new
dog.walk
dog.greet

owner names the home of a method

method(:greet) builds a handle for the greet method. owner reports Animal, the class where greet is written.

class Animal
  def greet
    puts "hello from Animal"
  end
end
class Dog < Animal
end
dog = Dog.new
puts dog.method(:greet).owner

The first match wins

Both classes write greet, and Dog comes first in the chain. The dog answers with the Dog version, and owner confirms it.

class Animal
  def greet
    puts "hello from Animal"
  end
end
class Dog < Animal
  def greet
    puts "hello from Dog"
  end
end
dog = Dog.new
dog.greet
puts dog.method(:greet).owner

Example

module Walker
  def walk
    puts "walks along"
  end
end
class Animal
  def breathe
    puts "breathes in and out"
  end
  def greet
    puts "hello from Animal"
  end
end
class Dog < Animal
  include Walker
  def greet
    puts "hello from Dog"
  end
end
p Dog.ancestors
dog = Dog.new
puts dog.method(:walk).owner
puts dog.method(:breathe).owner
puts dog.method(:greet).owner
dog.walk
dog.breathe
dog.greet

Key points

  • A search starts in the class of the object itself.
  • The search then moves through any mixed-in modules.
  • After that it climbs through the parent classes.
  • The first matching method found along the chain is the one that runs.
  • ancestors prints the whole chain as class and module names.
  • method with a symbol names a method, and owner says where it lives.

In this example, the ancestors line shows the full search order for Dog. owner places walk in Walker, breathe in Animal, and greet in Dog. Each call then runs the first match found along that chain.

Note

The chain explains why a child override beats a parent method.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A method is written in both Dog and its parent Animal. Which version runs for a dog?