- class Tree
- attr_accessor :energy
- def initialize
- @number_of_leaves = 0
- @number_of_branches = 0
- end
- def photosynthesize(sunlight)
- @energy = sunlight**@number_of_leaves
- end
- def eat_dirt
- @energy += 1
- end
- def grow_branch(number)
- @number_of_branches += number
- @energy -= number * 10
- end
- def grow_leaf(number)
- if @number_of_branches < 1
- p "Needs branches for the leaves"
- else
- @number_of_leaves += number
- @energy -= number
- end
- end
In the example above I've created a Tree class. Classes are the blueprints from which objects are made. Creating an object from a class is called instantiating. New Tree objects are instantiated with the syntax:
Every instance(object) of the Tree class will automatically have all of the methods, and within those methods are a couple different types of variables. The two types of variables I used here are local variables and instance variables.
The local variables begin with a lowercase letter or underscore, and represent a value in the method that they were created in. If I tried to access the variable called "sunlight" from outside the photosynthesize method it would not recognize it.
The instance variables are started with @ and can be accessed by any method contained within the instance of the class. This is why @number_of_leaves can be accessed outside of the initialize method, where it was first defined.
Every time I create a new tree, in addition to receiving the methods, the initialize method will automatically be called. This causes any new tree to begin with 0 leaves and 0 branches. Because of the lack of energy gathering leaves, new trees must "eat_dirt" until they have accumulated enough energy to "grow_branch" and then "grow_leaf". Trying to grow a leaf without having a branch will just be a waste of energy.
This is how the maple_tree object from the Tree class would operate.
=> maple_tree.eat_dirt # 1 energy
=> maple_tree.eat_dirt # 2 energy
=> maple_tree.eat_dirt # 3 energy
=> maple_tree.eat_dirt # 4 energy
=> maple_tree.eat_dirt # 5 energy
=> maple_tree.eat_dirt # 6 energy
=> maple_tree.eat_dirt # 7 energy
=> maple_tree.eat_dirt # 8 energy
=> maple_tree.eat_dirt # 9 energy
=> maple_tree.eat_dirt # 10 energy
=> maple_tree.grow_branch(1) # 0 energy (costs 10/branch)
=> maple_tree.eat_dirt # 1 energy
=> maple_tree.grow_leaf(1) # 0 energy (costs 1/leaf)
=> maple_tree.photosynthesize(10) # 10 energy (generates 10/leaf)
=> maple_tree.grow_leaf(10) # 0 energy
=> maple_tree.photosynthesize(10) # 100 energy
This is why it takes little trees so long to get big and strong.