Search code examples
rubyoperatorsmonkeypatching

Defining custom operators in ruby


I would like to be able to define custom operators. Is that possible? For example, to make a***b mean something.

Is it also possible to monkey patch existing operators? To, for example, make a**b always return a float?


Solution

  • Yes, you can. For example:

    class Fixnum
      def **(x)
        self.*(x)*1.0
      end
    end
    
    5**4 #==> 20.0