2

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?

Nemo157
  • 3,559
  • 19
  • 27

2 Answers2

1

Take a look at Ruby's coerce feature.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • See also ["In Ruby, how does coerce actually work?"](http://stackoverflow.com/questions/2799571/in-ruby-how-does-coerce-actually-work) – Phrogz Jan 17 '11 at 00:34
1

You want #coerce

something like

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

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

EnabrenTane
  • 7,428
  • 2
  • 26
  • 44