Course of Raku / Objects, I/O, and exceptions / Classes and objects / Methods / Exercises / A walking robot
Solution: A walking robot
Here is a possible solution to the task.
Code
class Robot {
has $.position is rw = 0;
method move($steps = 1) {
$.position += $steps;
}
}
my $r = Robot.new;
$r.move(5);
$r.move;
$r.move(2);
say $r.position;🦋 You can find the source code in the file bank-account.raku.
Output
8Comments
The
positionattribute isis rwso that the method can change it, and it defaults to0so a fresh robot starts at the origin.The
movemethod gives its parameter a default value,$steps = 1. The bare call$r.movetherefore advances by one step, while$r.move(5)and$r.move(2)advance by the amount given. The three calls add5 + 1 + 2, so the final position is8.