What is self part 2



In my previous post I talked about the differences in Class methods and Instance methods as a way of explaining how the keyword "self" is used. For example:




Now we are going to talk about how we use self inside of a method. 

When we refer to self inside of a method, it is talking about the current instance of the class. 


Here's an example:




So, what's going on? 
Well, we created a car class with a name, model and year

We have our initialize method on line 4 which says that when we create an instance of our class (line 19), that we are providing that information when we create the instance. 

On line 10, we have an instance method, print_out_car that prints (puts) out the instance as shown on line 21. 

On line 12, we are printing out the name assigned to the instance, in this case it is the string "Bobby", Next we print (puts) the model, "Aston Martin" and on line 14 we print (puts) out the year. 

This is how we can use self inside of a method.



Comments

Popular Posts