This content originally appeared on DEV Community and was authored by krisperu
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
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
If you wanted to call on the class method, this would be the result:
> Example.class_method
=> "This is a class method"
If you wanted to call on the instance method, you would get the following:
> Example.instance_method
=> undefined method "instance_method" for Example:class
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"
What would happen if you tried to call your class method on you instance?
> instance.class_method
=> undefined method `class_method' for #<Example:0x00007f8b609291c0>
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
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")
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
- Cover Image
- Ruby Docs
- Ruby - Classes and Objects
- Differences between class and instance methods in Ruby
- Defining instance methods
- Ruby: class methods vs. instance methods
- Instances and Instance Variables in Ruby Programming
- Read This If You Want to Understand Instance Variables in Ruby
This content originally appeared on DEV Community and was authored by krisperu
krisperu | Sciencx (2022-03-18T20:58:19+00:00) Class and Instance Methods in Ruby. Retrieved from https://www.scien.cx/2022/03/18/class-and-instance-methods-in-ruby/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.