2

vector * scalar对于我正在编写的几何库,我想支持向量乘以标量,只需定义Vector#*方法就很容易做到。然而,为了支持scalar * vector所有的Fixnum#*,Bignum#*Float#*方法必须是猴子补丁。我为这些类中的每一个使用以下代码来实现这一点:

class Fixnum
  old_times = instance_method(:'*')

  define_method(:'*') do |other|
    case other
    when Geom3d::Vector
      Geom3d::Vector.new(self * other.dx, self * other.dy, self * other.dz)
    else
      old_times.bind(self).(other)
    end
  end
end

class Bignum
  #...
end

class Float
  #...
end

我想知道是否有更好的方法来实现这一点,或者这样做是否有任何潜在的问题?

4

2 回答 2

1

看看 Ruby 的强制功能

于 2011-01-16T23:24:21.733 回答
1

你想要#coerce

就像是

class Geom3d::Vector
    def coerce(right_hand_side)
       self,right_hand_side
    end
end

http://corelib.rubyonrails.org/classes/Vector.html

于 2011-01-16T23:27:39.330 回答