Eli Sadoff Eli Sadoff - 14 days ago 6
Ruby Question

Can I overload/create a postfix unary operator?

I'd like to create two unary-postfix operators

!
and
!!
for the class
Numeric
in ruby. I have it defined like this so far

class Numeric
def !
(1..self).inject(:*)
end

def !!
if self.even?
(2..self).step(2).inject(:*)
else
(1..self).step(2).inject(:*)
end
end
end


However, this means that I must call
5.!
and
5.!!
. I know that you can define unary prefix operators such as
+@
and
-@
, but I was wondering if I could define a unary postfix operator so I can call
5!
and
5!!
instead of
5.!
and
5.!!
.

Answer

No. First, there are no postfix operators in Ruby, so the parser couldn't identify one. Secondly, even if we had postfix operators, a trailing exclamation mark is part of a method name, so if you have in your program a foo!, it would be interpreted as method foo!, not as foo with ! applied.