ruby operator overloading question

后端 未结 2 1628
逝去的感伤
逝去的感伤 2021-02-05 16:52

i\'ve been messing around with ruby and opengl for entertainment purposes, and i decided to write some 3d vector/plane/etc classes to pretty up some of the math.

simplif

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 17:24

    I believe the following will do what you want, though banister's suggestion to use coerce instead of monkey-patching Numeric is a preferred method. Use this method only if necessary (for example if you only want some binary operands to be transitive).

    Fixnum.class_eval do
      original_times = instance_method(:*)
      define_method(:*) do |other|
        if other.kind_of?(Vec3)
          return other * self
        else
          return original_times.bind(self).call(other)
        end
      end
    end
    

提交回复
热议问题