DEV Community

Cover image for Class and Instance Methods in Ruby
krisperu
krisperu

Posted on • Updated on

Class and Instance Methods in Ruby

What is a Method

A method in Ruby is a block of code that performs tasks. They are one of the most basic and important building blocks in Ruby. They can take an input, return an output, make calculations and many other things.

def sing_queen
    "Don't stop me now"
end
Enter fullscreen mode Exit fullscreen mode

Each method begins with the def keyword and end with an 'end'. The logic for the operation you are trying to execute is located in the body of the method. Each method requires a name which you can use to call the method as often as you need. Different parameters can be passed into the methods. Methods can add functionality to objects, classes and instances. A regular method adds functionality to an object, a class method adds functionality to classes, and instance methods add functionality to instances.

Class and Instance Methods

class Example
    def self.class_method
        "This is a class method"
    end

    def instance_method
        "This is an instance method"
    end 
end
Enter fullscreen mode Exit fullscreen mode

If you wanted to call on the class method, this would be the result:

> Example.class_method
=> "This is a class method"
Enter fullscreen mode Exit fullscreen mode

If you wanted to call on the instance method, you would get the following:

> Example.instance_method
=> undefined method "instance_method" for Example:class
Enter fullscreen mode Exit fullscreen mode

You would get an error because you are trying to call an instance method on a class. To get it to work, you need to create an instance of the class.

> instance = Example.new
> instance.instance_method
=> "This is an instance method"
Enter fullscreen mode Exit fullscreen mode

What would happen if you tried to call your class method on you instance?

> instance.class_method
=> undefined method `class_method' for #<Example:0x00007f8b609291c0>
Enter fullscreen mode Exit fullscreen mode

You would be unable to do so.

Class

So, what is class? Class is an object type. It is like a blueprint to create individual objects. As an example, let's take a look at a song. Some variables for a song can be an artist, a genre, a name, and an album. These variables make each song unique. So, in this instance we can create a class called song, and inside the class define individual object methods for artist, genre, and album. The class variable is accessible from your objects. The class variable is a characteristic of that class. They are identified by the @@ sign and variable name "@@variable".

Instance

Instance variables are identifiable by the @ sign before their variable. You can only access an instance variable inside the object. You cannot call on an instance method or access the instance variable outside the object. Let's go back to our example of song. Many different songs exist, and they can vastly differ from each other, but they all share certain characteristics. Each song has a name, artist, genre, and album, these are the objects inside our class. But every separate song is an example of an instance. "Don't stop me now" is an example of an instance. Let's take a look at the code.

class Song
    attr_accessor :name, :artist, :genre, :album

   @@genres =[]

    def initialize(name, artist, genre, album)
        @name = name
        @artist = artist
        @genre = genre
        @album = album
        @@genres << genre
    end

    def self.genres
        @@genres.uniq
    end

    def name_declaration
        "Name: #{name}"
    end
end

newsong = Song.new("We Will Rock You", "Queen", "Rock", "News
 of the World").name_declaration
Enter fullscreen mode Exit fullscreen mode

Here we are creating a new instance called "newsong" and assigning it the object variables previously declared. We can create as many of these as we like. We are also calling the instance method "name_declaration" on it. This will return the name of the song instance we just created.
We can create a new song instance without adding the instance method.

othersong = Song.new("Bohemian Rhapsody", "Queen", "Progressive Rock", "A Night at the Opera")
Enter fullscreen mode Exit fullscreen mode

We can also observe the class variable in the example above. The genres class variable will contain all the genres of all the songs you create. The declaration of genres with the two @ signs before it identifies it as a class variable. The @@genres << genre line of code shovels each genre from each song into the empty array declared above. And the class method of self.genres will filter the genres to ensure the resulting array of genres doesn't have any duplicate data.

Final Thoughts

Whoever named the class method and instance method, made it easy to be able to understand which method applied to which type. The names don't leave much room for interpretation, which is a good thing in this case. The easier it is to understand something, the easier it will be to implement it. Understanding the difference between class and instance takes a little more effort, but when you can differentiate the two, it makes creating classes and instances more straightforward. Deciding whether you need a class or instance method becomes as easy as just looking at the name of what you are trying to manipulate.


Sources

Latest comments (0)