Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Bad News: Your Program Hits the Big Time

Bad News: Your Program Hits the Big Time

Suppose even more success has befallen your pond simulator, and new requirements are pouring in faster than ever. The most pressing request is to extend this program to model other types of habitats besides ponds. In fact, a jungle simulation seems to be the next order of business.

Clearly, this change calls for major surgery on the code. You obviously will need classes for the jungle animals (perhaps tigers) and the jungle plants (mainly trees):

class Tree
  def initialize(name)
    @name = name
  end

  def grow
    puts("The tree #{@name} grows tall")
  end
end

class Tiger
  def initialize(name)
    @name = name
  end

  def eat
    puts("Tiger #{@name} eats anything it wants.")
  end

  def speak
    puts("Tiger #{@name} Roars!")
  end

  def sleep
    puts("Tiger #{@name} sleeps anywhere it wants.")
  end
end

You also need to change your Pond class’s name to something more appropriate for jungles as well as ponds. Habitat seems like a good choice:

jungle = Habitat.new(1, Tiger, 4, Tree)
jungle.simulate_one_day

pond = Habitat.new( 2, Duck, 4, WaterLily)
pond.simulate_one_day

Other than the name change, Habitat is exactly the same as our last Pond implementation (the one with the plant and animal classes). We can create new habitats in exactly the same way that we did ponds.

  • + Share This
  • 🔖 Save To Your Account