Explaining Object Orientated Ruby Concepts: class methods, instance methods and self
In object-orientated programming, a class is a blueprint for creating objects. Objects are data structures where an instance is an object created from a particular class. Once you have objects you want them to do stuff. Objects have a state, defined behaviors and a way to modify their state. Methods are how an object expresses its behavior and serve as the primary way it communicates with other objects. In Ruby there are class methods, and instance methods.An instance method provides functionality to one instance of a class and the other provides functionality to an object.
The easiest method to define I think are instance methods:
attr_accessor :text, :createdAt, :_id
Instance methods only work with an instance and thus you have to create a new instance to use them like
Next up we have class methods which are used for anything that does not deal with an instance of a class. The most commonly used way is:
puts ‘class method’
Self represents is a keyword that gives you access to the current object. The current object depends on where you are in your code at a given moment. If your code is inside an instance method self refers to the instance of the class. While in a class method the class “owns” the method self and points back to the class.