Unary operator

Hi all,

here is a novice’s question: I am wondering how to equip a class with
a unary operator. Defining a method “-” like this

class Something

def -
# some code
end

end

I have to call “-” by writing
somethingelse = something.-

Is there a possibility to write this in prefix notation?
somethingelse = -something

Thanks in advance, best,

Stephan

stephan.zimmer wrote:

Hi all,

here is a novice’s question: I am wondering how to equip a class with
a unary operator. Defining a method “-” like this

The method name for unary - is -@, and the method name for unary + is
+@.

stephan.zimmer wrote:

end
Thanks in advance, best,

Stephan

Hi Stephan,
This shows binary and unary operator definitions.
Hope it helps.

class Sam
attr_accessor :me

def initialize(me='This is a default: ')
@me = me
end

“Binary Operator”
def + (arg)
self.me + arg.to_s
end

“Unary operator”
def -@
self.me.reverse
end
end

x = Sam.new('Test ')
p x + ‘Test’
p -x

Cheers,
Steve