

Class and Instance Methods in Ruby
source link: https://dev.to/krisperu/class-and-instance-methods-in-ruby-49jp
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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
Recommend
-
87
auto-bind Automatically bind methods to their class instance It also correctly binds inherited properties. If you're targeting Node.js 12 and later or the browser, you should consider using
-
14
Most of Ruby’s fame is due to it’s dynamic capabilities. In Ruby you can define and redefine methods at runtime, create classes from nowhere and objects from pure dust. Most of these dynamical features are done using one of those methods at t...
-
23
Python Instance, Class, and Static Methods ExplainedIt’s easier than you thought!
-
8
In a previous Ruby Magic, we figured out how to reliably inject modules into classes by overwriting its .new method, allowi...
-
16
Why I can not delete a class instance in python advertisements I want to delete a class instance or make it None in python. But I'm not able t...
-
13
Make an instance of the Singleton Class object eligible for GC advertisements I have a class JAXBReader which hold unmarshalled xml fi...
-
9
Where is a private instance variable of an abstract class created in the heap? advertisements abstract class A { private int a;...
-
8
Don't call instance methods statically July 25, 2017 There are quite a few things in PHP 4 that were a bit stran...
-
8
JEP445 Instance main() methods coming for Java 21 LTS Java 21 is only a few weeks away from release. One of the changes that I think is the most interesting and I’m surprised that it’s taken this long to be in...
-
7
Don't call instance methods statically July 25, 2017 There are quite a few things in P...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK