Initializer in Coffeemaker
In the last few lessons we wrote code like this.
coffee1 = Coffeemaker.new coffee1.serve("hot")
This works but it would be nice when we are creating the instance we can give some values to it.
For example we should be able to say to the
Cofeemaker that make a hot coffee. Right now what we are doing
is that we are asking
Coffeemaker to make a coffee and then we are asking the instance to be “hot”.
We should be able to do this.
coffee1 = Coffeemaker.new("hot") coffee1.serve
Ruby has a special method called
initialize is called when
a class creates an instance.
So far we had not been making use of
but now are going to make use of the
initialize method is in all the classes sitting at the top doing nothing.
In reality our
CoffeeMaker looks like this.
class CoffeeMaker def initialize end end
When we are doing
Coffeemaker.new("hot") we are passing argument “hot” to the initialize method.
So far we have not been using it but now let’s use it.