Skip to content

Instantly share code, notes, and snippets.

@fj
Created February 29, 2012 16:16
Show Gist options
  • Save fj/1942091 to your computer and use it in GitHub Desktop.
Save fj/1942091 to your computer and use it in GitHub Desktop.
Exercise 43-1

Fruit baskets

Here is a Fruit class. Each fruit has a name and a number of calories.

class Fruit
  def initialize(fruit_name, calories)
    @fruit_name = fruit_name
    @calories = calories
  end
end

Put this in a fruit.rb file in some folder.

Exercises

Do these exercises one at a time. Show your entire fruit.rb class each time, and show your console output with a couple of examples of the new piece you add in each step.

  1. Change the initializer of Fruit so that if you don't provide a calories argument, we default to 100 calories.
  2. Enhance the Fruit class so that you can get the name of a Fruit instance.
  3. Enhance the Fruit class so that you can get the number of calories of a Fruit instance.
  4. Enhance the Fruit class so that you can set the name of a Fruit instance to another name.
  5. Create a new, empty class called FruitBasket in the same file.
  6. Enhance the FruitBasket class so that you can initialize it with an array of Fruits.
  7. Enhance the FruitBasket class so that you can get the number of items in the FruitBasket.
  8. Enhance the FruitBasket class so that you can get the total number of calories of all the fruits in the basket.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment