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
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With