[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Unary operator

stephan.zimmer

10/5/2008 9:44:00 PM

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
2 Answers

Tim Hunter

10/5/2008 9:52:00 PM

0

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 +@.


--
RMagick: http://rmagick.ruby...

Steve Messamore

10/6/2008 6:59:00 PM

0

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