Skip to content

Instantly share code, notes, and snippets.

@mariusbutuc
Forked from nickhoffman/rover.rb
Last active April 22, 2016 22:31
Show Gist options
  • Save mariusbutuc/5be2519628c35efeffc96ed3eff749f4 to your computer and use it in GitHub Desktop.
Save mariusbutuc/5be2519628c35efeffc96ed3eff749f4 to your computer and use it in GitHub Desktop.
Mars Rover code kata
class Rover
class InvalidDirection < StandardError
def message
'Vertigoooooo!'
end
end
VALID_DIRECTIONS = %i(north south east west).freeze
attr_accessor :ns_coordinates, :ew_coordinates, :direction
def initialize(direction: :north, ns_coordinates: 0, ew_coordinates: 0)
@direction = direction
@ns_coordinates = ns_coordinates
@ew_coordinates = ew_coordinates
end
def move
case direction
when :north
@ns_coordinates += 1
when :south
@ns_coordinates -= 1
when :west
@ew_coordinates += 1
when :east
@ew_coordinates -= 1
else
fail InvalidDirection
end
end
def turn(towards)
fail InvalidDirection unless VALID_DIRECTIONS.include?(towards)
@direction = towards
end
def coordinates
[ns_coordinates, ew_coordinates]
end
end
require './3_mars_rover.rb'
rover = Rover.new
7.times { rover.move }
rover.turn(:east)
3.times { rover.move }
rover.turn(:south)
2.times { rover.move }
rover.turn(:west)
rover.move
puts "Rover is at #{rover.coordinates} facing #{rover.direction}"
  1. #attr_accessor gives us the combined advantages of both #attr_reader and #attr_writer. Cool! Wait, += don't seem to work as expected! What's happening behind the scenes, does it not unfold into = and +?

  2. How do we convey the meaning of coordinates in a way that doesn't require the user of our interface to have knowledge of the code within? Is it a Cartesian plane? Both Nick and I started with the same assumption. But Mark's background in building video games drove his decision on coordinates in quite a different direction. Both Tessa and Haani, based on their frontend development expertise, mentioned that even SVG versus canvas consider coordinates differently. Imagine that!

  3. What happens when you're passing a constant as the default value upon initialization? I was surprised to see that multiple instances actually reference the same object in memory. So when one changes, this ripples to the other instances as well. Definitely not what I expected, and definitely not the desired behaviour in this case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment