Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Operator overloading in Ruby
3.
Operator overloading in Ruby Examples 
3.1.
Example1
3.2.
Example 2
4.
Frequently Asked Questions
4.1.
What is Ruby?
4.2.
Is Operator overloading in Ruby allowed?
4.3.
How to show Ruby's flexibility using operators?
4.4.
Why does Ruby not support Method overloading?
4.5.
Can sizeof operator overload in Ruby?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

Operator overloading in Ruby

Author yuvatimankar
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Ruby Logo

Ruby is a dynamic, open-source programming language that focuses on productivity and simplicity. The syntax of Ruby is natural and easy to understand for the users. Ruby is a popular language for many things, from web development to data analysis. Ruby programming language is highly flexible, and due to its flexibility, developers can change how the language works. Ruby is an interpreted language. 

In this article, we are going to discuss operator overloading in Ruby and some of the examples which are handling operator overloading in Ruby. So stay till the end!

Operator overloading in Ruby

Operator overloading in Ruby

Operator overloading in Ruby

Operator overloading allows us to provide an intuitive interface to users of our class; in addition, operator overloading makes it possible for templates to work equally with built-in types as well as with classes. Operator overloading in Ruby is applicable as it allows to define how an operator shall be used in a particular program. Operator overloading in Ruby allows developers to use standard operations in our custom classes. For example, we can define the '+ 'operator to perform subtraction instead of addition and vice versa.

Operator overloading in Ruby is allowed in the following operators: +, /, *, -, %, **, etc and operators that cannot be overloaded are: |, ||, &.&&,(), {}, etc.

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

Operator overloading in Ruby Examples 

In this section, we will see various examples of operator overloading in Ruby.

Example1

In the below example, we will perform operator overloading on the "+" operator. As we know, two user-defined data types cannot be added together, but due to operator overloading, it is possible. To see that we are creating the below program.

class CodingNinjas
    attr_accessor:name, :color   #instant variables
 
 
    def initialize(name, color)     # constructor
        @name = name
        @color = color
    end


    # (+) operator us overloading in this method
    def +(other_object)        
        return CodingNinjas.new("#{self.name}#{other_object.name}",
                  "#{self.color}#{other_object.color}")
    end
end

# Objects of class
a = CodingNinjas.new("ninja", "Red")
b = CodingNinjas.new("studio", "blue")

# Caling method
puts (a+b).inspect

 

Output:

#<CodingNinjas:0x0055afdca56900 @name="ninjastudio", @color="Redblue">

 

In the above example, we have created a class called CodingNinjas with two instant variables: name and color. And as we can see "+" operator is overloaded and gave us the concatenated results.

Example 2

This program is operator overloading in ruby by an integer. We will pass the integer and perform certain operations by overloading different operators such as "+", "**", and "/".

class Test
    attr_accessor:num
 
    # Initialize the num
    def initialize(num)
        @num = num
    end
 
    # Define + to do addition
    def +(other_object)
        return @num+other_object
    end
 
    # Define / to do Multiplication
    def /(other_object)
        return @num/other_object
    end
    def **(other_object)
        return @num**other_object
    end
end
a=Test.new(12)
puts a + 2
puts a / 2
puts a ** 2

 

Output:

14
6
144

 

As we can see, we have used operator overloading of three different operators to produce the above output. We have created a class called Test, in which, by using methods, we have overloaded different operators.

Frequently Asked Questions

What is Ruby?

Ruby is a high-level interpreted programming language that supports many programming paradigms. It was designed with programming productivity and ease of usage in mind.

Is Operator overloading in Ruby allowed?

Yes, Operator overloading in Ruby is allowed. Ruby allows users to define how an operator should be used in a particular program.

How to show Ruby's flexibility using operators?

Ruby is a flexible language since it allows users to modify its components freely. The plus (+) operator, for example, is used to execute addition. However, if you prefer to use the more readable word plus, you may add a method to Ruby's Numeric class.

Why does Ruby not support Method overloading?

In method overloading, binding of methods takes place during compile time, and as Ruby is a dynamically typed language, it does not support static binding, due to which method overloading is not allowed in Ruby.

Can sizeof operator overload in Ruby?

No, the sizeof operator cannot be overloaded in ruby because built-in operations like incrementing a pointer into an array implicitly depend on it.

Conclusion

This article extensively discussed the introduction of Ruby and operator overloading in Ruby. We started with a brief introduction of Ruby, operator overloading in Ruby, and then we saw some examples in which we have used operator overloading.

If you want to learn more on such topics, you can see History of Ruby8 reasons why Ruby should be your first languageDocumentation of Ruby, and Ruby vs. Python. also, you can visit our website, Coding Ninjas!

You can also refer to our guided path on Coding Ninjas Studio to upskill yourself in Data structure and algorithmsCompetitive Programming, Javascriptand System Design.

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

Happy learning!

Conclusion
Previous article
Nonoperators in Ruby
Next article
Operator Precedence in Ruby
Live masterclass