Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: overload operator behaviour for some cases only

My question is: how do I overload an operator on a builtin class (such as Integer.new.+) but only for some cases, depending on the class of the second operand

This is the behaviour I'm looking for:

myObject = myClass.new
1 + myObject #=> special behaviour
1 + 2        #=> default behaviour (3)

For example, in Python I would define a __radd__ method on myClass to override case 1.

I've tried using super but apparently Numeric doesn't have operator methods.

Ideally, what I'm looking for is a way to extract the + method and rename it.

Like this:

class Integer
  self.plus = self.+  # you know what i mean, I don't know how else to express this.
                      # I also know that methods don't work like this, this is just to
                      # illustrate a point.
  def + other
    other.class == myClass ? special behaviour : self.plus other
  end
end

Thanks for your help

like image 294
Asone Tuhid Avatar asked Feb 05 '23 16:02

Asone Tuhid


1 Answers

Both approaches posted here so far are a legacy Rails way, which is plain wrong. It relies on the fact that the class has no method called plus and nobody will reopen the class to create a method called plus. Otherwise things will go mad.

The correct solution is Module#prepend:

Integer.prepend(Module.new do
  def + other
    case other
    when Fixnum then special_behaviour
    else super(other)
    end
  end
end)
like image 180
Aleksei Matiushkin Avatar answered Mar 07 '23 08:03

Aleksei Matiushkin