In this section we will learn what the self-keyword is and how to use it in Ruby.
What is self keyword in Ruby?
The self keyword is used within the body of instance methods and it represent the object that is invoking the target method.
We use self-keyword specially when there’s a local variable in a method and an instance variable or an instance method with the same name.
Basically, when there is similarity between names in the body of a method, it’s hard for Ruby to differentiate between what’s what and we might get an error because of this confusion!
For example, let’s say you have a getter method name first_name and a local variable with the same name. Now within the body of the method that has such a local variable, let’s say we want to call the first_name method! How does Ruby know whether we’re calling a local variable or the method with the same name?!
This is where we can use the self keyword!
By prefixing the self-keyword to an instance method, Ruby knows that we want to call an instance method with the specified name which belongs to the current object that is calling the enclosing method.
Alright, it might seem a little confusing at first but when we get into an example, you’ll see how easy it is the concept of the self-keyword.
Ruby self Keyword Syntax:
self.instance_method_name
The use of self keyword is within the body of an instance method. For example, if there’s a method named “get_name” and it belongs to an object named emp, we can use the self keyword within the body of that method. Now in this body, the self-keyword represents the emp object. This means if the object has another method like get_lastname for example, we can call self.get_lastname which is equal to emp.get_lastname and it will return the result of calling the get_lastname method.
Example: using the self keyword in Ruby
class Person
attr_accessor :first_name, :last_name, :id, :company
def initialize(first_name, last_name, id, company = "Google")
self.first_name = first_name
self.last_name = last_name
self.id = id
self.company = company
end
end
prs = Person.new("John","Doe",500)
puts prs.first_name, prs.last_name, prs.id, prs.company
How does self keyword work in Ruby?
Note that within the body of the initialize method we have name collision! Basically, the name of parameters is equal to the name of the setter and getter methods in the Person class.
So in order to differentiate between the names of parameters and instance methods, we prefixed the names of instance methods with the self keyword to say these are the instance methods and not the parameters.
Again the self keyword represents the object that invoked the enclosing method! So for this example, the prs object invoked the initialize method and so the self keyword is representing the prs object within the body of the initialize method.