Commit 936eb06

mo k <mo@mokhan.ca>
2012-08-11 23:17:29
convert switch to separate commands.
1 parent 053a7ad
Changed files (2)
lib/navigate_rover.rb
@@ -10,14 +10,7 @@ class NavigateRover
     terrain = create_terrain(@plateau_size)
     rover = terrain.deploy_rover_to(@heading, @x, @x)
     @instructions.split(//).each do |instruction|
-      case(instruction)
-      when 'M'
-        rover.forward
-      when 'L'
-        rover.turn_left
-      when 'R'
-        rover.turn_right
-      end
+      commands_for(rover).find { |item| item.matches(instruction) }.run
     end
     rover
   end
@@ -25,4 +18,41 @@ class NavigateRover
     coordinates = plateau_size.split(' ')
     Plateau.new(coordinates[0], coordinates[1])
   end
+  def commands_for(rover)
+    [MoveForward.new(rover), TurnLeft.new(rover), TurnRight.new(rover)]
+  end
+end
+
+class MoveForward
+  def initialize(rover)
+    @rover = rover
+  end
+  def run
+    @rover.forward
+  end
+  def matches(item)
+    'M' == item
+  end
+end
+class TurnLeft
+  def initialize(rover)
+    @rover = rover
+  end
+  def run
+    @rover.turn_left
+  end
+  def matches(item)
+    'L' == item
+  end
+end
+class TurnRight
+  def initialize(rover)
+    @rover = rover
+  end
+  def run
+    @rover.turn_right
+  end
+  def matches(item)
+    'R' == item
+  end
 end
lib/plateau.rb
@@ -1,7 +1,7 @@
 class Plateau
   def initialize(x,y)
     @map = {:x => x, :y => y}
-    @headings = [North.new, East.new, West.new, South.new]
+    @directions = {:N => North.new, :E => East.new, :W => West.new, :S => South.new}
   end
 
   def move_forward( heading, location)
@@ -25,11 +25,6 @@ class Plateau
   end
 
   def deploy_rover_to(heading, x, y)
-    Rover.new(heading_for(heading), {:x => x, :y => y}, self)
-  end
-
-  private 
-  def heading_for(pneumonic)
-    @headings.find { |heading| heading.to_s == pneumonic }
+    Rover.new(@directions[heading.to_sym], {:x => x, :y => y}, self)
   end
 end