Skip to content

Instantly share code, notes, and snippets.

@andychongyz
Forked from nextacademy-private/orange_tree.rb
Last active October 12, 2015 10:29
Show Gist options
  • Save andychongyz/05bf0563b9ffd3d6d409 to your computer and use it in GitHub Desktop.
Save andychongyz/05bf0563b9ffd3d6d409 to your computer and use it in GitHub Desktop.
require 'byebug'
class Orange
attr_reader :diameter
# Initializes a new Orange with diameter +diameter+
def initialize
@diameter = rand(10)+1
end
end
# This is how you define your own custom exception classes
class NoOrangesError < StandardError
end
class OrangeTree
attr_reader :height, :age
def initialize
@age = 1
@height = 0
@oranges = []
end
# Ages the tree one year
def age!
@age += 1
@height += 1
#add random amount(1-50) of orange to oranges array start from age 4
if @age > 4
(rand(50)+1).times do
@oranges << Orange.new
end
end
end
# Returns +true+ if there are any oranges on the tree, +false+ otherwise
def any_oranges?
if @oranges.length > 0
return true
else
return false
end
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
return @oranges.shift
end
def dead?
@age >= 15
end
end
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
while tree.any_oranges?
basket << tree.pick_an_orange!
end
# It's up to you to calculate the average diameter for this harvest.
avg_diameter = 0
basket.each do |orange|
avg_diameter += orange.diameter
end
avg_diameter /= basket.length
puts "Year #{tree.age} Report"
puts "Tree height: #{tree.height} feet"
puts "Harvest: #{basket.size} oranges with an average diameter of #{avg_diameter} inches"
# 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