diff options
| author | mo k <mo@mokhan.ca> | 2012-02-11 15:29:04 -0700 |
|---|---|---|
| committer | mo k <mo@mokhan.ca> | 2012-02-11 15:29:04 -0700 |
| commit | d7a2e10529ebed062252b304dcb9c25e788b58ae (patch) | |
| tree | c803cdada0cc6a28bb27a576a63c4bfc24a6f8dd /lib | |
| parent | 98ce5e0dc03d01ddc9eae9029833c86446b94b72 (diff) | |
refactor conditional to polymorphism
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/rover.rb | 84 |
1 files changed, 64 insertions, 20 deletions
diff --git a/lib/rover.rb b/lib/rover.rb index 5b0e6fb..2f48cb5 100644 --- a/lib/rover.rb +++ b/lib/rover.rb @@ -1,29 +1,73 @@ class Rover - attr_reader :heading - def initialize(heading) - @heading = heading + @heading = Direction.find(heading) + end + def heading + @heading.direction end def turn_right - if(@heading == :north) - @heading = :east - elsif @heading == :east - @heading = :south - elsif @heading == :south - @heading = :west - elsif @heading == :west - @heading = :north - end + @heading = @heading.turn_right + end + def turn_left + @heading = @heading.turn_left + end +end + +class North + def direction + :north + end + def turn_right + East.new + end + def turn_left + West.new + end +end +class East + def direction + :east + end + def turn_right + South.new end def turn_left - if(@heading == :north) - @heading = :west - elsif @heading == :east - @heading = :north - elsif @heading == :south - @heading = :east - elsif @heading == :west - @heading = :south + North.new + end +end +class West + def direction + :west + end + def turn_right + North.new + end + def turn_left + South.new + end +end +class South + def direction + :south + end + def turn_right + West.new + end + def turn_left + East.new + end +end + +class Direction + def self.find(heading) + if(heading == :north) + return North.new + elsif heading == :east + return East.new + elsif heading == :south + return South.new + elsif heading == :west + return West.new end end end |
