Created
October 12, 2012 23:45
-
-
Save idlehands/3882314 to your computer and use it in GitHub Desktop.
Young and Brent's OrangeTree with notes
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
class OrangeTree | |
HEIGHT_GROWTH = 10 | |
FERTILE_AGE = 10 | |
MAX_AGE = 100 | |
=begin | |
Try setting up a method instead of a constant to avoid issues with over-defining if you ever | |
need need a sub-class. | |
example: | |
def height_growth | |
10 | |
end | |
Then you can call height_growth just like you would if it was a variable or a constant. | |
=end | |
def initialize | |
@height = 0 #shouldn't need a variable, it could just be a method that calculates from age | |
@age = 0 | |
@oranges = 0 | |
@growth_count = 0 | |
end | |
def height | |
# in inches. calculate to inches and feet | |
feet, inches = @height.divmod(12) | |
converted_height(feet, inches) | |
end | |
def converted_height(feet, inches) | |
str = "" | |
str += "#{feet} feet " if feet > 0 | |
str += "#{inches} inches" if inches > 0 | |
end | |
def one_year_passes | |
@age += 1 | |
@height += HEIGHT_GROWTH # This could be a | |
oranges_fall_off # this should be unnecessary if you write your produce_fruit correctly | |
produce_fruit | |
death | |
end | |
def count_the_oranges | |
@oranges | |
end | |
def oranges_fall_off # See note above. | |
@oranges = 0 | |
end | |
def produce_fruit # Overall, this is good and you're calling it at a good time. | |
return if @age < FERTILE_AGE | |
# Produce the same amount of oranges as its age if the tree is old enough. | |
# If the tree is past the peak, growth slow down. | |
@age <= MAX_AGE / 2 ? @growth_count = @age : @growth_count -= 1 | |
@oranges += @growth_count | |
end | |
def pick_an_orange # Works | |
if @oranges == 0 | |
"No more oranges to pick!" | |
else | |
@oranges -= 1 | |
"The orange was juicy!" | |
end | |
end | |
def death # This should just return True/False. If you want to output anything, | |
# you probably should have a different method to do that. | |
if @age >= MAX_AGE | |
@oranges = 0 # Since you ideally would | |
"Tragedy! The tree is dead!" | |
end | |
end | |
end | |
orange = OrangeTree.new | |
orange.one_year_passes | |
puts orange.height | |
puts orange.count_the_oranges | |
1.upto(20) do | |
orange.one_year_passes | |
puts "Orange count:" | |
puts orange.count_the_oranges | |
puts "Height:" | |
puts orange.height | |
end | |
1.upto(40) do | |
orange.one_year_passes | |
puts "Orange count:" | |
puts orange.count_the_oranges | |
puts "Height:" | |
puts orange.height | |
orange.pick_an_orange | |
puts "Orange count:" | |
puts orange.count_the_oranges | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment