diff --git a/lib/tree.rb b/lib/tree.rb index 6c54019..ab4a054 100644 --- a/lib/tree.rb +++ b/lib/tree.rb @@ -1,25 +1,44 @@ class NoApplesError < StandardError; end -class AppleTree - attr_#fill_in :height, :age, :apples, :alive +class Tree + attr_accessor :height, :age, :apples, :alive def initialize + @height=0 + @age=0 + @apples=[] + @alive=true end def age! + @age += 1 + if @age > 50 + @alive=false + return + end + + @height += 1 + self.add_apples end def add_apples + num_apples = rand(1..5) * @age + 1 + num_apples.times do + @apples.push(Apple.new('red', rand(1..3))) + end end def any_apples? + @apples.size > 0 end def pick_an_apple! raise NoApplesError, "This tree has no apples" unless self.any_apples? + @apples.pop end def dead? + not @alive end end @@ -29,10 +48,12 @@ def initialize end end -class Apple < - attr_reader #what should go here +class Apple < Fruit + attr_reader :color, :diameter def initialize(color, diameter) + @color=color + @diameter=diameter end end @@ -61,7 +82,7 @@ def tree_data diameter_sum += apple.diameter end - avg_diameter = # It's up to you to calculate the average diameter for this harvest. + avg_diameter = basket.size > 0 ? diameter_sum / basket.size : 0 puts "Year #{tree.age} Report" puts "Tree height: #{tree.height} feet" @@ -76,4 +97,4 @@ def tree_data end # Uncomment this line to run the script, but BE SURE to comment it before you try to run your tests! -# tree_data +tree_data diff --git a/spec/tree_spec.rb b/spec/tree_spec.rb index 99c9184..9b27057 100644 --- a/spec/tree_spec.rb +++ b/spec/tree_spec.rb @@ -2,13 +2,69 @@ require 'tree' describe 'Tree' do - it 'should be a Class' do - expect(described_class.is_a? 'Class').to be_true + let(:tree) { Tree.new } + + it 'should be a Tree' do + expect(tree.class).to be Tree + end + + it 'should age' do + current_age = tree.age + tree.age! + new_age = tree.age + expect(new_age == current_age + 1).to be true + end + + it 'should grow apples' do + current_apples = tree.apples.size + tree.add_apples + new_apples = tree.apples.size + expect(current_apples < new_apples).to be true + end + + it 'should report if the tree has any apples' do + tree.add_apples + expect(tree.any_apples?).to be true + end + + it 'should be able to have apples picked' do + 10.times do + tree.add_apples + end + current_apples = tree.apples.size + tree.pick_an_apple! + new_apples = tree.apples.size + expect(new_apples == current_apples - 1).to be true + end + + it 'should die after 50 years' do + 51.times do + tree.age! + end + expect(tree.dead?).to be true end end describe 'Fruit' do + let(:fruit){Fruit.new} + + it 'should be a Fruit' do + expect(fruit.class).to be Fruit + end end describe 'Apple' do + let(:apple){Apple.new('red', 2)} + + it 'should be an Apple' do + expect(apple.class).to be Apple + end + + it 'should be red' do + expect(apple.color == 'red').to be true + end + + it 'should have diameter 2' do + expect(apple.diameter == 2).to be true + end end