Course of Raku / Objects, I/O, and exceptions / Classes and objects / Methods / Exercises / A reversed word

Solution: A reversed word

Here is a possible solution to the task.

Code

class Word {
    has $.text;

    method reversed {
        $.text.flip;
    }
}

say Word.new(text => 'Raku').reversed;

🦋 You can find the source code in the file greeter.raku.

Output

ukaR

Comments

  1. The reversed method reaches the object’s own text through its accessor $.text and calls the built-in flip on it, which returns the string reversed.

  2. The method is called directly on the freshly created Word object. Nothing is stored back — reversed simply computes and returns a new value from the attribute.

  3. Note that inside the class, you can read the variable directly without employing the accessor:

    method reversed {
        $!text.flip;
    }

Course navigation

A reversed word   |   Rectangle area