From: GOTO Kentaro Date: 2001-09-28T15:17:00+09:00 Subject: [ruby-talk:21797] Re: Help: how to (re)define the unary minus? From: furufuru@ccsr.u-tokyo.ac.jp (Ryo Furue) Subject: [ruby-talk:21795] Help: how to (re)define the unary minus? Date: Fri, 28 Sep 2001 14:48:36 +0900 > Hi there, > > I'm wondering how one should (re)define the unary minus operator for a > class. The following fails: A way is to define -@. > Note that what I want to create is not a complex class; I've used it > as an obvious example. If your target is a kind of Numeric, the following may help: class X < Numeric def initialize(x) @val = x end attr_reader :val def -(x) case x when Integer, Float X.new(@val - x) when X X.new(@val - x.val) else a, b = x.coerce a - b end end def coerce(x) case x when Integer, Float [X.new(x), self] else raise TypeError end end end p -X.new(2) # default -@: # 0 - X.new(2) ==> a,b = X.new(2).coerce(0) ==> a - b