Today, we will be discussing what does 'self' means in Ruby and how it can be used in the code?
What is self ?
Everything we write in Ruby belongs a particular Object, 'self' is nothing but an object in ruby.'self' is a keyword in Ruby which gives us access to the current object.
'self' points to the currently executing code in a Object. If your code is executing in Animal class as shown below then 'self' is that Animal instance.
Using self in instance method
- current_instance_animal method returns self which is Animal instance that we created in line number 9
- Line number 11 proves that 'self' == lion
Using self in class method
- To access a instance method as shown in above figure, we must create an instance of that class and call the method using that instance.
- To access a class method which is defined using self we do not need to create an instance of that class but can directly call that method using Example.class_method
Top comments (0)