Sunday, 9 December 2012

Operator Overloading in Ruby

I expect many of you know that Ruby permits Operator overloading .Many of Ruby's operators are implemented as methods, you can define or redefine how these methods or  operators should work in your own classes , here i am trying to mention some fun facts that we can do with ruby.

I expect all of you should be knowing this , may be better than me as well . But this is a just a simple but strait forward example for the beginners like me,  those who wanted to experiment more on Ruby. 

Creating a class called ClassA

class ClassA
  attr_accessor :value
  def initialize(value)
    @value = value
     puts "Object of ClassA with value #{@value} has been created"
  end
 end
and Instantiating one obj of ClassA,

a=ClassA.new(10)
Object of ClassA with value 10 has been created
What if ruby permits a behavior like you can add objects of 2 different classes , then you are receiving the output without creating any scene , it will be fun right.


Creating another class called ClassB,

class ClassB
  attr_accessor :value
  def initialize(value)
    @value = value
     puts "Object of ClassB with value #{@value} has been created"
  end
 end
and instantiating the ClassB obj like,

b=ClassB.new(20)
Object of ClassB with value 20 has been created

Now we are overloading the behavior of '+' operator by defining a function like ,

class ClassA
  attr_accessor :value
  def initialize(value)
    @value = value
     puts "Object of ClassA with value #{@value} has been created"
  end
  def +(obj)
    return ClassA.new(self.value + obj.value)
  end
 end

class ClassB
  attr_accessor :value
  def initialize(value)
    @value = value
     puts "Object of ClassB with value #{@value} has been created"
  end
  def +(obj)
    return ClassB.new(self.value + obj.value)
  end
 end

What will happen if we are performing an addition using these 2 objects a & b,

c = a + b

the fun begins here,

try to print c.value you will get the value 30,

How this magic happens ,

Operators are just methods in Ruby ,  all the arithmetic operators are behaves like methods and we are passing values as arguments , like in the above example a + b , we are calling the method called '+' and passing b as an argument  . This is same with all the arithmetic operators.

If you have created 3rd class also like ClassC, and have created obj c = ClassC.new(30)
You will get the results while trying all the possible way like,

a+b+c
a+(b+c)
(a+b)+c

No comments:

Post a Comment