Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Concept of Ruby OOPs
3.
Ruby Class
4.
Ruby Objects
5.
Method Definition
6.
Instance Methods and Variables
7.
Class Methods and Variables
7.1.
Class Methods
7.2.
Class Variables
8.
Ruby Inheritance 
9.
Ruby Constructors 
10.
Frequently Asked Questions
10.1.
Explain Ruby object
10.2.
How to create a Ruby object?
10.3.
Explain Ruby class
10.4.
What are the mixins in Ruby?
10.5.
What are the characteristics of Constructors?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

Ruby is an object-oriented language

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

Introduction

This blog will learn about some essential OOP concepts such as encapsulation, polymorphism, inheritance, and abstraction. We will also learn about Classes, Objects, and Methods; this blog will help you understand more about Ruby OOPs.

Classes & Objects | Ruby | Tutorial 29 - YouTube

Source: youtube.com

Concept of Ruby OOPs

Ruby is a truly object-oriented programming language that can be embedded in Hypertext Markup Language (HTML). In Ruby, everything is an object. The Ruby programming language is based on the ideas of objects and data. An object comprises all integers, strings, and even classes.

A class specifies an object's form by combining data representation and methods for modifying that data into a single package. Class members are the data and methods that make up the class.

Object-oriented programming (OOPs) is a programming paradigm that uses objects and their interactions to create applications and computer systems.

The following are some fundamental OOP concepts:

Encapsulation

It hides a class's implementation details from other objects, making it inaccessible to the rest of the code. Its primary goal is to safeguard data from being manipulated.

Polymorphism

It's the ability to express an operator or function in various ways depending on the data provided.

Inheritance

It generates new classes from existing ones. The behaviors of a new class are inherited from its parent class, which is referred to as a superclass. Predefined classes can be made more reusable and helpful in this way.

Abstraction

It hides a class's complexity by modeling classes relevant to the task.

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

Ruby Class

A Ruby class defines the blueprint of a data type. It defines the meaning of the class name.

A class definition begins with the keyword class, then the class name, and finishes with a keyword end.

A capital letter must always be used to begin a class name. More than one word is run together in a class name, with each word capitalized and no separating letters.

For example, using the keyword class, we define a Ruby class as follows:

Class Ruby
     Code
End 

Ruby Objects

Everything in Ruby is an object. When we make objects, we use methods to connect with them. As a result, an object is made of both data and methods.

To build an object, we must first declare a class. A single class can be used to make a large number of objects. The new keyword is used to declare objects.

For example, using the keyword new, we define Ruby objects as follows:

object1 = Ruby.new
object2 = Ruby.new

Method Definition

The def keyword is used to define a Ruby method, followed by the method name. Finally, we must use the end keyword to indicate that the Method has been declared.

For example, using the keyword def, we define Ruby Method as follows:

Def methodName
    Code…………………
End

Instance Methods and Variables

The instance methods are also declared using the def keyword and may only be used with a class instance.

The instance methods are defined in the same way as any other method using the def keyword, and they may only be used with a class instance, as illustrated below.

Def getArea(l, w)
 @length, @width = l, w
End 

 

Here @length and @width are Instance Variables. 

Instance Variables are class characteristics that become object properties when objects are generated using the class.

Class Methods and Variables

Let us discuss about class methods and variables in Ruby.

Class Methods

Class Methods are methods specified within the class; public class methods can also be accessed via objects.

When a method is defined outside the class declaration, it is tagged as private by default. Methods are designated public by default, as indicated in the class specification.

def class_method_name
     code
end

Class Variables

Class Variables are variables defined within the class that only the class method has access to. Class variables begin with @@ and must be initialized before being used in method declarations.

Syntax:

@@variable_name = value

Ruby Inheritance 

The concept of inheritance is one of the most essential in object-oriented programming.

Inheritance enables us to define one class in terms of another, making it easier to plan and manage applications. In easier terms, we create new classes using predefined classes.

Inheritance also allows for the reuse of code functionality and quick implementation time; however, Ruby does not enable many levels of inheritance; nonetheless, Ruby does provide mixins.

Classes that are newly developed are referred to as derived classes, while classes from which they are derived are referred to as base classes. With inheritance, code may be reused several times, reducing program complexity.

In Ruby, < character is used to create a subclass. The syntax is shown below:

parentClass < subClass 

 

Let's look at an example to help you understand even more: -

class Parent   
  
    def initialise   
        puts "This is Parent class "   
    end   
end   
  
class Child < Parent   
  
   def initialize
       super   
       puts "This is Child class "   
   end   
end   
  
Parent.new   
Child.new 

 

Output:

This is Parent class
This is Parent class
This is Child class

 

In the above example, There are two generated classes. The first is the base Parent class, while the second is the derived Child class. The super Method invokes the Parent class.

We instantiate both classes using the last two lines.

In Output, the Parent class is formed first, and then the Derived Child class is also called the constructor of its parent class, and finally, the Child class is generated.

Ruby Constructors 

A constructor is automatically called when an object is created. They do not produce any return values. They are known as initializing in Ruby.

A constructor can also contain a set of instructions or a procedure that will be executed when the object is created.

Syntax:

def initialise (parameter_list)
 Code
end

 

Let's understand it with an example:

class Parent   
  
    def initialise   
        puts "Parent is created"   
    end   
  
end   
  
Parent. new   

 

As we've finished explaining, let's look at some frequently asked questions about Ruby OOPs.

Check out this article - Compile Time Polymorphism

Frequently Asked Questions

Explain Ruby object

The initial root of all Ruby objects is an object. Ruby objects derive from BasicObject, allowing for the creation of alternative object hierarchies. An object is made of both data and methods, Or in other words, we can say.

Classes are used to build objects. Consider classes to mold and objects to be the products of those molds. Individual objects will have distinct information than other objects, despite the fact that they are instances of the same class.

How to create a Ruby object?

In Ruby, objects are created by invoking the class's new Method. It is a distinct type of Method that is predefined in the Ruby library.

Syntax:

objectName= className.new  

Explain Ruby class

A class specifies the shape of an item by combining data description and methods for modifying that data into a compact package. Members of a class are the data and methods included within it. 

When you create a class, you are creating a blueprint for a data type. But to define a class, its definition goes as a class begins with the keyword class, is followed by the class name, and is terminated by a period.

What are the mixins in Ruby?

A mixin is a specialized version of multiple inheritances that inherits only the interface part.

Although Ruby does not allow multiple levels of inheritance, it does support mixins.

What are the characteristics of Constructors?

Among the most significant features of constructors are: - 

  • Constructors are used to setting up instance variables.
  • Unlike in most programming languages, the constructor in Ruby has a distinct name.
  • The initialize and def keywords are used to define a constructor.
  • Ruby treats it as a unique method.
  • In Ruby, constructors can be overloaded.
  • Constructors cannot be passed down.
  • It returns the class's instance.

Conclusion

In this article, we learned about Ruby OOPs, including what is Ruby Class, objects, Constructors, and Ruby Inheritance. After reading about Ruby OOPs, 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 Object Marshalling in RubyTainting Objects in Ruby, and Object References in Ruby.

Recommended Reading:

Four Pillars of OOPS

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

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

Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass