0

在 Ruby 中,操作

point - 20     # treating it as point - (20,20)
20 - point     # treating it as (20,20) - point

将被实施。

但是下面的代码:

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 - q.x, @y - q.y)
  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)

p p - q
p q - p

p p * 3
p 5 * p

p p - 30
p 30 - p

输出:

#<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实际上将被p - 30强制功能视为。它可以工作吗?

我实际上很惊讶该-方法不会以这种方式强制参数:

class Fixnum
  def -(something)
    if (/* something is unknown class */)
      a, b = something.coerce(self)
      return -(a - b)   # because we are doing a - b but we wanted b - a, so it is negated
    end
  end
end

也就是说,该函数返回 anegated version of a - b而不是仅仅返回a - b

4

1 回答 1

1

减法不是交换操作,因此您不能只交换您的操作数coerce并期望它起作用。coerce(something)应该返回[something_equivalent, self]。所以,在你的情况下,我认为你应该Point#coerce这样写:

def coerce(something)
  if something.is_a?(Fixnum)
    [Point.new(something, something), self]
  else
    [self, something]
  end
end

你需要稍微改变其他方法,但我会把它留给你。

于 2010-05-10T11:52:15.533 回答