Let’s talk about self(and methods), baby.
As I move on from the first phase of my course and prepare to take on the 2nd, I felt it was appropriate to harp on a few things I was still struggling to grasp. A big part of Object Oriented Ruby is the object part. When creating a program, it’s super important to be able to differentiate between a class and instance method in order to utilize them accordingly. Here I’ll be taking a dive into self and how to better understand class/instance methods.
To distinguish between a class method and an instance method, first we need to look at the method definition — or signature. A class method typically starts with either self
or the class name, and it usually only refers to that class in all contexts, but not to any individual instances of that class. An example of this can be seen below:
class Cat
def self.meow #self belongs to the Cat class
self
end
endCat.meow == Cat # => true
Here I’ve created a meow class method of Cat. With class methods, the class itself “owns” the method. In this instance, self is pointing to the class Cat. When you’re dealing with an instance method, it will look like any regular method you create, and can be referenced by all instances of that class, but not directly by the class object itself. Here meow would belong to the object created via Cat.new, and referencing to self would only point to a particular instance that is being executed.
class Cat
def meow #this is an instance method
self
end
endgarfield = Cat.new #this is also saying Cat.new.meow
garfield.meow == garfield # => true
So, to decide whether to use an instance or a class method, ask yourself whether you’re dealing with one object or many. Think of it like this: one instance : Instance Method! Class itself : Class Method! Then make sure to put your self
accordingly!
Extra tid bit: A few cool things about self
is that you don’t need to use the class name for each class method definition, making the code more fluid in case you need to change the class name. You can also use self
in an instance method when you have a local variable with the same name. Since local variables take precedent, using self
will call the method instead of printing the value of the variable.
Hope this helps you as much as it did me! Happy coding!