In Ruby operation
point - 20
must be implemented.
But the following code:
class Point attr_accessor :x, :y def initialize(x,y) @x, @y = x, y end def -(q) if (q.is_a? Fixnum) return Point.new(@x - q, @y - q) end Point.new(@x - qx, @y - qy) end def -@ Point.new(-@x, -@y) end def *(c) Point.new(@x * c, @y * c) end def coerce(something) [self, something] end end p = Point.new(100,100) q = Point.new(80,80) p (-p) pp - q pq - p pp * 3 p 5 * p pp - 30 p 30 - p
Output:
#<Point:0x2424e54 @x=-100, @y=-100> #<Point:0x2424dc8 @x=20, @y=20> #<Point:0x2424d3c @x=-20, @y=-20> #<Point:0x2424cc4 @x=300, @y=300> #<Point:0x2424c38 @x=500, @y=500> #<Point:0x2424bc0 @x=70, @y=70> #<Point:0x2424b20 @x=70, @y=70> <--- 30 - p the same as p - 30
30 - p
will actually be taken as p - 30
by the coerce function. Is it possible to make it work?
I am really surprised that the method -
will not give an argument in this way:
class Fixnum def -(something) if (/* something is unknown class */) a, b = something.coerce(self) return -(a - b)
that is, the function returns a negated version of a - b
instead of just returning a - b
.
ruby class
太極 者 無極 而 生 May 10 '10 at 8:19 2010-05-10 08:19
source share