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
我想知道是否有更好的方法来实现这一点,或者这样做是否有任何潜在的问题?