Search code examples
rubymonkeypatching

Is there a better way to "monkey-patch" Ruby's base classes?


For a geometry library I'm writing I want to support multiplication of vectors by scalars, easy enough to do for vector * scalar by just defining the Vector#* method. However to support scalar * vector all the Fixnum#*, Bignum#* and Float#* methods have to be monkey-patched. I'm using the following code for each of these classes to accomplish that:

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

I'm wondering if there's any better way to accomplish this, or if there are any potential problems with doing this?


Solution

  • Take a look at Ruby's coerce feature.