-
-
Save samkahchiin/6d3de67ee2c9b31b993c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is how you define your own custom exception classes | |
class NoOrangesError < StandardError | |
end | |
class OrangeTree | |
def initialize | |
@age = 0 | |
@orange_on_tree = [] | |
@height = 0 | |
puts "Orange is growing!" | |
end | |
attr_reader :age, :height | |
# Ages the tree one year | |
def age! | |
@age += 1 | |
if @age <= 60 | |
@height += 10 | |
end | |
@orange_on_tree = [] | |
if @age > 5 && @age < 60 | |
a = rand(1..10) | |
a.times do | |
@orange_on_tree << Orange.new | |
end | |
end | |
end | |
def dead? | |
if @age >= 60 | |
return true | |
else | |
false | |
end | |
end | |
# # Returns +true+ if there are any oranges on the tree, +false+ otherwise | |
def any_oranges? | |
# orange is older than certain age | |
# byebug | |
if @orange_on_tree == [] | |
false | |
else | |
true | |
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 | |
@orange_on_tree.shift | |
end | |
end | |
class Orange | |
# Initializes a new Orange with diameter +diameter+ | |
attr_reader :diameter | |
def initialize | |
@diameter = rand(3..5) | |
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 = [] | |
while tree.any_oranges? | |
basket << tree.pick_an_orange! | |
end | |
sum = 0 | |
basket.each {|orange| sum = sum + orange.diameter} | |
avg_diameter = sum / 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" | |
puts "" | |
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