Table of contents
1.
Introduction
2.
Defining a Simple Class
2.1.
A Class Method 
2.2.
Constants 
2.3.
Class Variables 
2.4.
Class Instance Variables 
3.
Frequently Asked Questions
3.1.
In Ruby, how do you define a class method?
3.2.
How should a class be structured in Ruby?
3.3.
What are ruby variables?  
3.4.
What are Class Instance Variables?
3.5.
How do Ruby classes work?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Let’s get dive deep into the classes of ruby

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A full-stack development framework created in the Ruby programming language is called Ruby on Rails, or even just Rails. It comes with all the resources needed to build fantastic web applications on both the front and back ends.

Rendering HTML templates, maintaining live pages through WebSockets, sending and receiving emails, enqueuing jobs for asynchronous work, storing uploads in the cloud, and offering strong security defences against typical threats. Rails has endless functionalities.

Rails in ruby

Let us now understand the concept of classes in Ruby.

Ruby is an object-oriented language in the purest meaning possible because each value in the language behaves like (or is) an object. Each object represents a certain class. An object responds to a set of methods that are defined by a class. Classes have the ability to extend, subclass, inherit, and override the methods of their superclass. Classes may also contain modules or inherit their methods from them.

Defining a Simple Class

To define a class in ruby there are some simple steps to be followed. Come now let us know how we will create a simple class. 

Defining a new class:🤓
 

 In Ruby a new class is often created by using the following syntax: 
 

class Class_name             # some code explaining the class behaviour
end                                # a class is terminated by end keyword

For ex-

class Ninja
	@@no_of_Ninja = 3             #class variables
end

 

The first letter of the class name needs to be capitalised. When a new class has formed an object of type Class is initialized and assigned to a global constant. 
 

Create instances of that class:🥷
 

Till now we haven’t put anything in our Ninja class yet, but we can still instantiate it:
 

p = Ninja.new 


Here, a class object that represents our new class is stored in the constant Ninja. A method called new that creates a new instance is present in all class objects.
 

Write an initializer method for the class:

 

Now here we want to initialize the objects with two variables when we create new Ninja objects. In many object-oriented languages, this can be accomplished by using a “constructor.” 

In Ruby, it is achieved with an initialize method. 

Let’s take a look at this example:
 

class Ninja
	def initialize(id,rank) 
		@ninja_id = id
		@ninja_rank = rank
	end                   #end of the method
end                   #end of the class Ninja

 

Add attribute accessor methods to the class:🤔
 

Two instance variables are used by our Ninja class. However, only other instance methods can access the value of these variables. We must offer accessor methods that return the values of the variables if we want users of the Ninja class to be able to use the id and rank:

Implementation

class Ninja 
	def initialize(id,rank)
		@ninja_id = id
		@ninja_rank = rank
	end
	def id    # The accessor (or getter) method for @id 
		@id 
	end 
	def rank       # The accessor method for @rank 
		@rank
	end 
end


Now that we know how to create class, initialise it and access it, we should now run a simple program

class Ninja
	#initialize method
	def initialize(coderid, rank)
		#variables
		@ninja_coderid = coderid
		@ninja_rank = rank
		#printing the output
		puts "coder is: #@ninja_coderid"
		puts "student is: #@ninja_rank"
		puts "\n"
	end #end of the method
end
ninja = Ninja.new("1", "1")


Output:


Define operators for the class


So now let us talk about operators. As we know that the + operator is used to perform vector addition of two Point objects. Similarly, the * operator multiplies a Point by a scalar.

Method-based operators, like +, are just methods with names that contain punctuation. Because the - operator has binary and unary variants.
 

Here is a definition of the mathematical operations for the Ninja class:

class Ninja
	attr_accessor :number
	# Initializing the number
	def initialize(number)
		@number = number
	end
	# here + operator will perform addition
	def + (obj)
		return @number + obj
	end
	# the * operator performs Multiplication
	def * (obj)
		return @number * obj
	end
	# the ** operator performs power 
	def ** (obj)
		return @number ** obj
	end
end
a = Ninja.new(12)
puts a + 6
puts a * 4
puts a ** 2


Output:

A Class Method
 

Let's try a different approach for adding Ninja objects. Let's create a method named sum that accepts any number of Ninja objects, adds them together, and returns a new Ninja. 

This method is not a Ninja object-invoked instance method. Instead, it is a class method that is called by the Ninja class itself. The sum method could be used in the following way:
 

total = Ninja.sum(n1, n2, n3)                            # n1, n2 and n3 are Ninja objects 


Constants
 

The definition of some associated constants is beneficial for many classes. The following constants could be helpful for our Point class:
 

class Point 
	def initialize(x,y)               # Initialize method 
		@x,@y = x, y 
	end 
	ORIGIN = Point.new(0,0)
	UNIT_X = Point.new(1,0) 
	UNIT_Y = Point.new(0,1) # Rest of class definition goes here
end

These constants can be referred to by their unqualified names inside the class definition.
 

Class Variables
 

Class variables are shared and observable by the class definition itself, the class methods, and the instance methods of a class. Class variables, like instance variables, are encapsulated; users of a class cannot see them; but, the implementation of a class may use them. The names of class variables start with  @@.
 

The code might be written as follows:

# Program in Ruby for a count of total topics in syllabus
class Exam
  
# class variable
@@total_count = 0
  
# class array
@@syllabus_list = []
  
def add_topics(topic)
  
    # adding topics to the syllabus array
    @@syllabus_list.push(topic)
    @@total_count += 1#counting
end
  
def print_topics
    puts "Total number of topics --> #@@total_count";
    puts "All topics --> #@@syllabus_list";
end
# direct access
def Exam.printtopics_only
    puts "\nExam.printtopics_only", @@syllabus_list.join("\n");
end
end
  
list = Exam.new()
  
list.add_topics("programming")
list.add_topics("DSA")
list.add_topics("DBMS")
list.add_topics("OOPS")
list.add_topics("SQL")
list.add_topics("Full Stack")
  
list.print_topics
  
# direct access
Exam.printtopics_only


Output:

 

Class variables are used in class methods, instance methods, and the class declaration itself, outside of any methods, which is something to keep in mind when looking at this code. Instance variables and class variables are fundamentally dissimilar.
 

Class Instance Variables
 

Classes are objects, and like other objects, they can have instance variables. Class instance variables, often known as class instance variables, are distinct from class variables. But because of their substantial similarities, class variables are often replaced by them.

A class instance variable is an instance variable that is used inside the class definition but not in the definition of an instance variable. Class instance variables, like class variables, are associated to the class as a whole rather than any specific instance of the class.

Let us now explore some of the examples to understand this concept:

class Calculator
  def plus(number, other)
    number + other
  end
  def minus(number, other)
    number - other
  end
  def multiply(number, other)
    number * other
  end 
  def divide(number, other)
    number.to_f / other
  end
end
calculator = Calculator.new
puts calculator.plus(5, 6)
puts calculator.minus(5, 7)
puts calculator.multiply(2, 8)
puts calculator.divide(4, 6)

 

Output

Frequently Asked Questions

In Ruby, how do you define a class method?

Public class methods can be accessed with the help of objects and are defined inside the class. When a method is defined outside of the class definition, it is by default marked as private. Methods are marked as public by default, as specified in the class definition.

How should a class be structured in Ruby?

Three things make up a Ruby object: a class, some instance variables, and a set of flags. A Ruby class is an object of the class Class, which includes all object-related objects as well as a list of methods and a reference to a superclass (which is itself another class).

What are ruby variables?  

Data that can be used later in a program is stored in ruby variables. The names of each variable, which functions as memory, vary. There are four types of variables in Ruby i.e, local variable, class variable, instance variable, and global variable. 

What are Class Instance Variables?

Instance variables are accessible across all methods for any given instance or object. That is, instance variables vary from object to object. Instance variables are denoted by the at sign (@) and the variable name.

How do Ruby classes work?

A class in Ruby is an object that defines a blueprint for creating other objects. Classes specify which methods are available to any class instance.

Conclusion

In this article, we have discussed Classes and Modules, Class Method, Constants, Class Variables and Class Instance Variables. We hope that this article has helped you enhance your knowledge regarding classes of Ruby. If you would like to learn more, check out our articles on Tainting Objects in RubyObject References in RubyRuby-langmore-on-ruby-langruby-lang.faqrubykoans and  many more. 

 

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Learning!

Live masterclass