There was useful information about the ancestors method in the book, so I summarized it.
Recognition so far
class Mountains
end
class Nepal < Mountains
def everest_place
"nepal"
end
end
p Nepal.ancestors
p Nepal.class.superclass.superclass.superclass
Output result
[Nepal, Mountains, Object, Kernel, BasicObject]
BasicObject
It is inconvenient to follow the inheritance relationship one by one with superclass. I realized that it would be convenient to use the ancestors method to retrieve everything from the current class to BasicObject as an array. (Including modules)
New recognition
module World
def everest_place
"china"
end
end
class Mountains
def everest_place
"india"
end
end
class Nepal < Mountains
include World
def everest_place
"nepal"
end
end
p Nepal.ancesters
nepal = Nepal.new
puts nepal.everest_place
as mentioned above, ❶ The Nepal class includes the World module, so you can use the Everest_place method of the World module. ❷ The Nepal class inherits the Mountains method, so you can also use the Everest_place method of the Moutains class.
** Suppose you have three everest_place methods, including the everest_place method in the Nepal class ** Of course, the output will change depending on which everest_place method is called.
The ancestors method is useful in such cases. Looking at the output of p Nepal.ancestors,
Nepal.Output result of ancestors
[Nepal, World, Mountains, Object, Kernel, BasicObject]
It will be displayed. ** Since it is called in order from the left, you can see that the everest_place method defined in the Nepal class is fetched. ** **
Let's actually see the result.
Output result
nepal
The return value of the everest_place method defined in the Nepal class has returned properly.
Recommended Posts