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.
Example:
class Album
def release_date=(date)
@release_date = date
end
def release_date
@release_date
end
endalbum = Album.new
album.release_date = 1991
album.release_date
# => 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.
def self.countend
Well that then raises another question, what is self?
Self is similar to the this keyword in JavaScript. The keyword self is a special variable that points to the object that "owns" the currently executing code. To put it all together a class variable and method would look like this:
class Album
@@album_count = 4
def self.count
@@album_count
end
end# You call it by writing:
Album.count
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!
-Jess