Skip to content

Instantly share code, notes, and snippets.

@zachgersh
Created July 22, 2013 20:38
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 zachgersh/6057458 to your computer and use it in GitHub Desktop.
Save zachgersh/6057458 to your computer and use it in GitHub Desktop.
# This is how you define your own custom exception classes
require 'debugger'
class NoOrangesError < StandardError
end
class OrangeTree
# Ages the tree one year
attr_accessor :dead, :oranges, :age, :height
def initialize
@height = 1
@age = 0
@oranges = 0
@dead = false
end
def age!
self.age += 1
self.dead = true if age > 25
self.oranges = age * 2 if age > 5
unless dead
self.height > 7 ? self.height += 1 : self.height *= 2
end
end
def dead?
dead
end
# Returns +true+ if there are any oranges on the tree, +false+ otherwise
def any_oranges?
return true if oranges > 0
false
end
# Returns an Orange if there are any
# Raises a NoOrangesError otherwise
def pick_an_orange!
raise NoOrangesError, "This tree has no oranges" unless self.any_oranges?
# orange-picking logic goes here
self.oranges -= 1
Orange.new(rand(3..10))
end
end
class Orange
# Initializes a new Orange with diameter +diameter+
attr_accessor :diameter
def initialize(diameter)
self.diameter = diameter
end
end
# THE DRIVER CODE - AYO
tree = OrangeTree.new
tree.age! until tree.any_oranges?
puts "Tree is #{tree.age} years old and #{tree.height} feet tall"
until tree.dead?
basket = []
# It places the oranges in the basket
# IT PLACES THE ORANGES IN THE BASKET
while tree.any_oranges?
basket << tree.pick_an_orange!
end
avg_diameter = basket.reduce(0){|sum, orange| sum += orange.diameter} / basket.size
puts "Year #{tree.age} Report"
puts "Tree height: #{tree.height} feet"
puts "Harvest: #{basket.size} oranges with an average diameter of #{avg_diameter} inches"
puts ""
# Age the tree another year
tree.age!
end
puts "Alas, the tree, she is dead!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment