Yes, you can. For example:
class Fixnum
def **(x)
self.*(x)*1.0
end
end
5**4 #==> 20.0
Question
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
OTHER TIPS
Custom operators? Not unless you want to hack the C parser (or Java parser for JRuby or ...). OTOH, operators are mostly syntactic sugar for methods and you're allowed to defined all the methods you want.
Since many operators (but not all) are just methods in disguise, you can monkey patch the implementations of existing operators as much as you want to. You'd have to track down all the numeric classes that define their own **
implementation and patch all of them; note that you'd need to cover Rational
, Complex
, ... from the core as well as things like BigDecimal from the standard library. I'd strongly recommend against doing this, you'd just be setting yourself up for pain and suffering; for example, what would you do with BigDecimal#**
when the result doesn't fit in a Float
? What about Complex#**
? If you need Float
s for something, make it explicit with a to_f
call.