有没有更好的方法来“修补”Ruby的基类?

时间:2011-01-16 23:14:51

标签: ruby monkeypatching

对于我正在编写的几何库,我想通过标量来支持向量的乘法,只需定义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

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

2 个答案:

答案 0 :(得分:1)

看一下Ruby的 coerce feature

答案 1 :(得分:1)

你想要#coerce

类似

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

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

相关问题