Ruby Class vs Instance Method
As I begin to instill the meanings and use of class and instance methods in Ruby, I wanted to share what I have learned and how to distinguish between the two.
So, what is an instance variable and instance method?
An instance variable is stored inside of a class and starts with a single @ symbol and is responsible for holding information regarding an instance. An instance method is defined inside of the class body and can only be called on a particular instance of that class.
@release_date = date
endalbum = Album.new
album.release_date = 1991
# => 1991
In the example above, @release_date is the instance variable and def release_date is the instance method. A new album instance was created by calling Album.new and set equal to a variable name album.
What is a class variable and class method?
A class variable is used to store values related to a class in general that is accessible to the entire class, rather than a particular instance and the syntax starts with @@. Class methods are used to implement behaviors that are related to a class in general rather than an instance. A class method is defined by using the self keyword. Self, when used for a class method, refers to the entire class itself.
Well that then raises another question, what is self?
@@album_count = 4
end# You call it by writing:
In the example above, @@album_count is the class variable and def self.count is the class method. Album.count will return the current count of albums which is 4.
Learning a programming language can be difficult but take it one line of code at a time and you’ll be fine. I hope this was helpful!