# Unary operator

**URL:** <https://www.ruby-forum.com/t/unary-operator/150203>\
**Category:** Ruby\
**Created:** [October 6, 2008, 1:32am UTC](https://www.ruby-forum.com/t/unary-operator/150203 "2008-10-06T01:32:00Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![stephan.zimmer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecccb3/32.png) [@stephan.zimmer](https://www.ruby-forum.com/u/stephan.zimmer)\
**Post date:** [October 6, 2008, 1:32am UTC](https://www.ruby-forum.com/t/unary-operator/150203/1 "2008-10-06T01:32:00Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![stephan.zimmer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecccb3/32.png) [@stephan.zimmer](https://www.ruby-forum.com/u/stephan.zimmer)\
**Post date:** [October 6, 2008, 1:36am UTC](https://www.ruby-forum.com/t/unary-operator/150203/2 "2008-10-06T01:36:06Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![stephan.zimmer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecccb3/32.png) [@stephan.zimmer](https://www.ruby-forum.com/u/stephan.zimmer)\
**Post date:** [October 6, 2008, 9:01pm UTC](https://www.ruby-forum.com/t/unary-operator/150203/3 "2008-10-06T21:01:06Z")

</div>

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](http://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
