Forum: Ruby Unary operator

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
stephan.zimmer (Guest)
on 2008-10-06 03:32
(Received via mailing list)
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
Tim H. (Guest)
on 2008-10-06 03:36
(Received via mailing list)
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
+@.
Steve Messamore (Guest)
on 2008-10-06 23:01
(Received via mailing list)
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
This topic is locked and can not be replied to.