Course of Raku / Objects, I/O, and exceptions / Classes and objects / Subroutines vs methods / Exercises / Triple as a method

Solution: Triple as a method

Here is a possible solution to the task.

Code

class Number {
    has $.n;

    method triple {
        $.n * 3;
    }
}

say Number.new(n => 7).triple;

🦋 You can find the source code in the file triple-method.raku.

Output

21

Comments

  1. As a method, triple belongs to the object and works with the object’s own n — nothing is passed in.

  2. Compared with the subroutine version, the data lives in the object instead of arriving as an argument. Both give 21.

Course navigation

Triple as a method   |   Quiz — Subs vs methods