diff --git a/lib/tree.rb b/lib/tree.rb index 962b72e..c4d4663 100644 --- a/lib/tree.rb +++ b/lib/tree.rb @@ -1,38 +1,67 @@ class NoApplesError < StandardError; end class Tree - attr_#fill_in :height, :age, :apples, :alive + attr_accessor :height, :age, :apples, :alive def initialize + self.height = 0 + self.age = 0 + self.apples = [] + self.alive = true end def age! + self.age += 1 + self.grow + self.add_apples + + if self.age > 20 + self.alive = false + end + end + + def grow + if self.height < 20 + self.height += 2 + end end def add_apples + if self.age > 3 + 5.times { self.apples.push(Apple.new("red", rand(3.0..4.5).round(2))) } + end end def any_apples? + self.apples.length > 0 end def pick_an_apple! raise NoApplesError, "This tree has no apples" unless self.any_apples? + apples.shift end def dead? + !self.alive end end class Fruit + attr_reader :has_seeds + def initialize - has_seeds = true + @has_seeds = true end end -class Apple < - attr_reader #what should go here +class Apple < Fruit + attr_reader :color, :diameter def initialize(color, diameter) + super() + + @color = color + @diameter = diameter end end @@ -61,7 +90,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 = (diameter_sum / basket.length).round(2) puts "Year #{tree.age} Report" puts "Tree height: #{tree.height} feet" diff --git a/spec/tree_spec.rb b/spec/tree_spec.rb index b4f44c6..a8df260 100644 --- a/spec/tree_spec.rb +++ b/spec/tree_spec.rb @@ -5,10 +5,66 @@ it 'should be a Class' do expect(described_class.is_a? Class).to eq true end + + let(:tree) { Tree.new } + + it "is initialized as a young tree" do + expect(tree.age).to eq(0) + end + + it "is alive" do + expect(tree.dead?).to be(false) + end + + it "can age" do + tree.age! + expect(tree.age).to eq(1) + end + + it "grows as it ages" do + tree.age! + expect(tree.height).to eq(2) + end + + it "doesn't have apples for 3 years" do + 3.times { tree.age! } + expect(tree.any_apples?).to be(false) + end + + it "starts producing apples after 3 years" do + 4.times { tree.age! } + expect(tree.any_apples?).to be(true) + end + + it "can be harvested for apples" do + 4.times { tree.age! } + expect(tree.pick_an_apple!).to be_instance_of(Apple) + end + + it "dies after 20 years" do + 21.times { tree.age! } + expect(tree.dead?).to be(true) + end end describe 'Fruit' do + it "has seeds" do + expect(Fruit.new.has_seeds).to be(true) + end end describe 'Apple' do + let(:apple) { Apple.new("red", 3.5)} + + it "has a color" do + expect(apple.color).to eq("red") + end + + it "has a diameter" do + expect(apple.diameter).to eq(3.5) + end + + it "has seeds" do + expect(apple.has_seeds).to be(true) + end end