How to change a lightbulb in Ruby

if !light
  # Try and switch the light on.
  light_switch.flick
end
 
# Still no light?
if !light
 
  # Is there an old lightbuld in the socket?
  if old_lightbulb.installed?
    old_lightbulb.remove.discard! :bin
  end
 
  # Try and find a new lightbulb.
  new_lightbulb = Lightbulb.find_by_torchlight,
    :locations => [:kitchen, :bathroom, :under_stairs]
 
  if new_lightbulb
 
    begin
      new_lightbulb.install
    rescue BurntFingers
      swear :lots
      # Switch the light OFF
      light_switch.flick
      retry
    end
 
    # Switch the light on.
    light_switch.flick
 
  else
    raise NoNewLightBulbsInTheHouseError.new "Go to the shops."
  end
 
end

Download this code: lightbulb.rb

Leave a Reply