Created
September 29, 2013 16:27
-
-
Save cnocon/6754036 to your computer and use it in GitHub Desktop.
From Chris Pine's Learn to Program: Orange tree. Make an OrangeTree class that has a height method that returns its height and a one_year_passes method that, 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 tre…
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
| class OrangeTree | |
| def initialize | |
| @age = 0 | |
| @height = 0 | |
| @orange_count = 0 | |
| @alive = true | |
| end | |
| def height | |
| if @alive | |
| @height | |
| else | |
| 'A dead tree isn\'t very tall. :(' | |
| end | |
| end | |
| def count_the_oranges | |
| if @alive | |
| @orange_count | |
| else | |
| "Dead trees don't have fruit..." | |
| end | |
| end | |
| def pick_an_orange | |
| if @alive | |
| if @orange_count == 1 | |
| @orange_count = @orange_count - 1 | |
| puts "You just ate the last delicious orange on this tree. There are 0 oranges left." | |
| elsif @orange_count > 1 | |
| puts "You just ate a delicious orange." | |
| @orange_count = @orange_count - 1 | |
| puts "There are #{@orange_count} oranges left to eat." | |
| else | |
| puts "Sorry, there aren't any oranges on this tree." | |
| end | |
| else | |
| "Dead trees don't produce fruit, sorry bud." | |
| end | |
| end | |
| def one_year_passes | |
| if @alive | |
| if @height < 40 | |
| @age = @age + 1 # tree ages tree one year | |
| @orange_count = 0 # all the oranges fall off | |
| @height = @height + rand(5) #tree grows taller/height increases | |
| if @age > 4 | |
| grow_fruit | |
| end | |
| puts "This year your tree is #{@height} feet tall, and has #{@orange_count} oranges. It is #{@age} years old." | |
| elsif @height >= 40 && rand(3) > 1 | |
| @alive = false | |
| puts "Your tree just died, son." | |
| end | |
| else | |
| "Your tree is still dead one year later." | |
| end | |
| end | |
| def has_fruit? | |
| if @alive | |
| if @orange_count > 0 | |
| true | |
| else | |
| false | |
| end | |
| else | |
| false | |
| end | |
| end | |
| def grow_fruit | |
| if @alive | |
| if @age <= 6 #between 4 and 6 | |
| @orange_count = @orange_count + 10 | |
| end | |
| if @age > 6 && @age < 10 #between 7 and 9 | |
| @orange_count = @orange_count + 20 | |
| end | |
| if @age >=10 && @age < 40 #between 10 and whatever | |
| @orange_count = @orange_count + 30 | |
| end | |
| else | |
| @orange_count = 0 | |
| end | |
| end | |
| end | |
| ot = OrangeTree.new | |
| 23.times do | |
| ot.one_year_passes | |
| ot.pick_an_orange | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment