Course of Raku / Objects, I/O, and exceptions / Classes and objects / The metaobject protocol 🆕 / Exercises / Add a method
Solution: Add a method
Here is a possible solution to the task.
Code
class Dog {
has $.name;
}
Dog.^add_method('speak', method { $.name ~ ' says woof' });
say Dog.new(name => 'Rex').speak;🦋 You can find the source code in the file add-a-method.raku.
Output
Rex says woofComments
.^add_methodattaches a new method to the class’s metaobject at runtime, given as an anonymousmethod { … }.The added method is a real method of the class, so inside it
$.namereaches the object’snameattribute, just as a method written in the class body would. After the call, everyDogresponds to.speak.
Course navigation
← Add a method | Input and output →