Course of Raku / Objects, I/O, and exceptions / Classes and objects / Introspecting objects / Exercises / Describe a class

Solution: Describe a class

Here is a possible solution to the task.

Code

class Animal {
}

class Dog is Animal {
}

say Dog.^name;
say Dog.^mro.elems;
say 'Cat'Dog.^mro.map(*.^name);

🦋 You can find the source code in the file describe-a-class.raku.

Output

Dog
4
False

Comments

  1. .^name returns the class’s own name, Dog.

  2. .^mro returns the inheritance chain, and .elems counts it. There are four types in the chain — Dog, its parent Animal, and the universal Any and Mu — so the count is 4.

  3. .^mro.map(*.^name) turns that chain into the list of type names, (Dog Animal Any Mu). The set-membership operator then checks whether Cat is one of them. Dog does not descend from any Cat, so the answer is False.

Course navigation

Describe a class   |   Count the attributes