Created
December 5, 2012 17:56
-
-
Save ready4god2513/4217908 to your computer and use it in GitHub Desktop.
Orange Tree Problem
This file contains 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
# Make an OrangeTree class. It should have a height method which returns its height, and a oneYearPasses method, | |
# which, when called, ages the tree one year. Each year the tree grows taller (however much you think an orange tree | |
# should grow in a year), and after some number of years (again, your call) the tree should die. For the first few years, | |
# it should not produce fruit, but after a while it should, and I guess that older trees produce more each year | |
# than younger trees... whatever you think makes most sense. And, of course, you should be able to countTheOranges | |
# (which returns the number of oranges on the tree), and pickAnOrange (which reduces the @orangeCount by one and | |
# returns a string telling you how delicious the orange was, or else it just tells you that there are no more | |
# oranges to pick this year). Make sure that any oranges you don't pick one year fall off before the next year. | |
class OrangeTree | |
attr_reader :height | |
HEIGHT_PER_YEAR = 2 | |
MAX_AGE = 6 | |
DEAD_TREE_MESSAGE = "The tree has died. :( No More Oranges" | |
def initialize | |
@age = 0 | |
@height = 2 | |
@oranges = [] | |
end | |
def oneYearPasses | |
if max_age_reached? | |
tree_dies | |
else | |
increment_age | |
increment_height | |
grow_fruit | |
@age | |
end | |
end | |
def orange_count | |
@oranges.count | |
end | |
def pick_orange | |
@oranges.pop || "No oranges left to pick" | |
end | |
def dead? | |
@age.frozen? | |
end | |
private | |
def tree_dies | |
@oranges.freeze | |
@age.freeze | |
@height.freeze | |
class << self | |
[:pick_orange, :orange_count, :oneYearPasses].each do |m| | |
define_method(m) { DEAD_TREE_MESSAGE } | |
end | |
end | |
DEAD_TREE_MESSAGE | |
end | |
def max_age_reached? | |
@age == MAX_AGE | |
end | |
def increment_age | |
@age = @age.next | |
end | |
def increment_height | |
@height = @age * HEIGHT_PER_YEAR | |
end | |
# Obviously not how trees produce, but it works | |
def grow_fruit | |
@oranges = [] # Need to reset the orange count each year | |
([(@age - 3), 0].max * 2).times { @oranges << Orange.new } | |
end | |
end | |
class Orange | |
def to_s | |
"Wow, that is an amazing orange" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment