What is self in Ruby part 1
What is self? (Part 1)
One of the
programming concepts I get stuck on is the concept of Self. In order
to fully understand Self, I will break this blog post into 2 parts.
1. Class vs instance
methods
2. Using self to
reference the current instance
So, lets start with
Class vs Instance methods
An instance method
is one that
An instance of a
class is when a class is initialized.
This is an
example of an instance method:
In the above code, we defined a class Test.
We created an initialize method that takes in a string called name
Our instance method is defined on line 8 and is called say_name
Inside of our instance method we print (puts) the value of our instance variable @name
On line 15, we create a new instance of our Test class. Since our initalize method takes in a value, we have to supply a value when we create a new instance. The value that we supplied is the string "Jennifer".
The result:
Hi my name is: Jennifer
Class methods are methods that operate on the class and not on an instance of the class.
Below is an example of what a class method looks like:
Class methods operate without an instance of the class.
On line 1 we define the class Test.
On line 3 we define the class method square which takes in an integer.
On line 10, we call that method, passing in the integer value that we want to multiply. That calls on the square method defined on line 3, multiplying the value passed in with itself and then assigning the value to the variable answer. The square method then prints (puts) the answer to the screen.
The result:
25
So, to recap, class methods work on the class itself. They cannot be called on an instance.
Instance methods work on an initialized instance of a class.
Comments
Post a Comment