Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Ruby Classes
3.
Defining a Class
4.
Variables in a Ruby Class
5.
Ruby Modules
6.
Module Namespaces
7.
Module Mixins
8.
Frequently Asked Questions
8.1.
Explain Ruby's class?
8.2.
Describe the Ruby module?
8.3.
Explain module mixins.
8.4.
What are Class Instance Variables?
8.5.
What are Class Global Variables?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Classes and Modules in Ruby

gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

In this blog, we'll learn about Classes and Modules in Ruby and then will learn about the Various fundamental terms in Classes and Modules in Ruby. If you have some prior understanding of these Classes and Modules in Ruby, that is fantastic; if not, that is not an issue at all because we will be addressing Classes and Modules in Ruby and terminology from the ground up. 

Modules and Classes in Ruby

Ruby Classes

Class is an instance of every Ruby class. Ruby classes are first-class objects.

Ruby classes are always preceded by the keyword class, followed by the class name. CamelCase is commonly used for class names. A capital letter should always be used to begin the class name. The class definition is completed utilizing the end keyword.

A class is a foundation upon which individual objects are built. Your bicycle is an instance of the class of objects known as bicycles in an object-oriented language.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Defining a Class

A class in Ruby always begins with the keyword class, followed by the class name. The name should always start with capital letters. The Ruby class might be shown as:

Syntax:

Class ClassName
  Codes……
end

 

Let's take an example for a better understanding of Classes

# defining class Sample
class Sample

# defining method
def ninja’s

# printing result
puts "Hello Guys!" 

# end of the method
end 

# end of class Sample
end

# creating object
obj = Sample.new 

# calling method using object
obj.ninja’s

 

Now let's learn and understand some theoretical Concepts such as Variables and their types. This can be of great use sometimes in theoretical questions related to Classes and Modules in Ruby.

Variables in a Ruby Class

So far, we've utilized several variables; now, let's define what a variable is

A variable is a symbol or a term that represents a value. Variables are used to store variables like as numeric numbers, characters, character strings, or memory addresses in memory so that they may be utilized in any portion of the program.

In a Ruby class, there are four fundamental sorts of variables, which are as follows:

Local Variables:- Local variables are variables defined within a procedure. Outside of the method, local variables are not accessible. More information on the approach will be provided in the following chapter. Local variables are denoted by a lowercase letter or _. 

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.

Class Variables:- Class variables are accessible across objects. A class variable is a class characteristic that belongs to the class. They are followed by the variable name and preceded by the symbol @@.

Global Variables:- Class variables cannot be shared between classes. If you want a single variable that is accessible across classes, you must declare a global variable. The dollar symbol ($) always precedes global variables.

Ruby Modules

A Ruby module is a grouping of methods and constants. A module method can be either an instance method or a module method.

When a module is included, instance methods are methods in the class.

Instance methods cannot be invoked without first generating an enclosing object, although module methods may.

They are comparable to classes in that they include a set of methods, class definitions, constants, and other modules. They are defined in the same way as classes are. Modules cannot be used to construct objects or subclasses. There is no module inheritance hierarchy.

Modules are used to organize methods, classes, and constants. Modules provide two key advantages.

  • Modules define a namespace and prevent name conflicts.
  • The mixin capability is implemented through modules.

 

Syntax:

module ModuleName
 Statement1
 Statement2
End

 

Note: The name of the module should begin with a capital letter

We've talked about Modules; now, let's talk about Module Namespace to have a better understanding of modules.

Module Namespaces

 A lot of reusable code is created while developing bigger files. These scripts are arranged into classes that may be added to a file.

For instance, suppose two people have the same method name in two separate files. Furthermore, both files must be included in a third file. The method name in both included files is the same, which may cause an issue.

The module mechanism is used here. Modules offer a namespace in which your methods and constants may be defined without being overridden by other methods and constants.

For better understanding, let's take the help of an example:

Assume we have established a number of various types of library books in file1.rb, such as adventure, horror, and so on.

We defined the number of novels reads and remained to read in file2.rb, including adventure novels.

We must load both files file1 and file2 in file3.rb. The module mechanism will be used in this case.

File1.rb

Module Library
num_of_books=100
Def Library.adventure(20)
#...
End
Def Library.horror(80)
#...
End
end 

 

File2.rb

Module Novel
total= 23
read= 5
Def Novel.adventure(left)
 #...
End
end 

 

file3.rb 

require “Library”
require “Novel”
 
x= Library.adventure (Library:: num_of_books)
y= Novel.adventure (Novel::total)

 

A module method is called by prefixing its name with the module's name and a period, while a constant is referenced by prefixing its name with the module name and two colons.

Module Mixins

Ruby does not natively enable multiple inheritances, but Ruby Modules have another fantastic usage. They effectively eliminate the requirement for various estates by offering a capability known as a mixin.

Because a module is not a class, it does not contain instances. A module, on the other hand, can be included within a class.

If you include a module within a class, the class gains access to the module's methods.

To better understand mixin, consider the following sample code:

module Name
   def John
   end
   def Olivia
   end
end
module Hometown
   def Paris
   end
   def London
   end
end

class Combination
include name
include Hometown
   def India
   end
end


Output:

Combination.new
Combination.John
Combination.Olivia
Combination.Paris
Combination.London
Combination.India

 

Module Name is made up of the methods John and Olivia. Module Hometown is made up of the methods Paris and London. Modules Name and Hometown are both included in the Combination class. The Combination class has access to all four methods, namely John, Olivia, Paris, and London. As a result, you can see that the class Combination derives from both modules. As a result, the class Combination exhibits multiple inheritances or a mixin.

We are done with the blog. Let’s see some FAQS related to it.

Frequently Asked Questions

Explain Ruby's class?

Ruby classes are instances of Ruby classes. Ruby classes are first-class objects. It always begins with the keyword class, followed by the name of the class.

Describe the Ruby module?

A Ruby module is a grouping of methods and constants. A module method can be either an instance method or a module method. They are comparable to classes in that they include a set of methods, class definitions, constants, and other modules. They are defined in the same way as classes are. Modules cannot be used to construct objects or subclasses. There is no module inheritance hierarchy.

The name of the module should begin with a capital letter.
Modules mainly fulfill two functions:
a) They serve as namespaces, and they avoid name conflicts. 
b) They enable the mixin feature to share functionality across classes..

Explain module mixins.

Ruby does not allow for multiple inheritances. In Ruby, modules use a mixin to reduce the requirement for multiple inheritances.

Because a module is not a class, it does not contain instances. A module, on the other hand, can be included within a class.

When you include a module within a class, the class gains access to the module's methods.

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.

What are Class Global Variables?

Class variables cannot be shared between classes. If you want a single variable that is accessible across classes, you must declare a global variable. The dollar symbol ($) always precedes global variables.

Conclusion

In this article, we learned about Classes and Modules in Ruby, including Variables of Class and Modules in ruby. Namespace and Mixins of Classes and Modules in ruby.

After reading about Ruby Classes and Modules in Ruby, are you not feeling excited to read/explore more articles on the topic of Ruby? Don't worry; Coding Ninjas has you covered. To learn, see Ruby OOPsTainting Objects in Ruby, and Object References in Ruby. You can also refer to the Official RubyRubyOfficial DocumentationRuby FAQ, and Ruby Koans.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! 

Do upvote our blogs if you find them helpful and engaging!

Thank you

Previous article
Regex and Range in Ruby
Next article
Modules in Ruby
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass