Skip to content

Instantly share code, notes, and snippets.

@futureperfect
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save futureperfect/7b58198c0ed322b3e33e to your computer and use it in GitHub Desktop.
Save futureperfect/7b58198c0ed322b3e33e to your computer and use it in GitHub Desktop.
Ruby Refactoring Exercise

Traffic Light Refactoring Exercise

The code contained in traffic_light.rb is a simple model for a traffic light. How can we refactor this? Pretend we have tests so we're actually refactoring and not just changing shit.

Note anything about what you observe in this code and how it drives your refactoring.

class TrafficLight
attr_reader :state
def change_state(state)
@state = state
end
def next_state
case @state
when "stop" then "proceed"
when "proceed" then "caution"
when "caution" then "stop"
end
end
def update_light
case @state
when "stop" then change_light("red")
when "proceed" then change_light("green")
when "caution" then change_light("yellow"); puts "Ring ring ring!"
end
end
def change_light(color)
puts "Light is now #{color}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment