From: Steve Messamore Date: 2008-10-07T03:58:14+09:00 Subject: Re: Unary operator 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 > > 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 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