ruby operator overloading question

后端 未结 2 1597
逝去的感伤
逝去的感伤 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:30

    Using coerce is a MUCH better approach than monkey-patching a core class:

    class Vec3
        attr_accessor :x,:y,:z
    
        def *(a)
            if a.is_a?(Numeric) #multiply by scalar
                return Vec3.new(@x*a, @y*a, @z*a)
            elsif a.is_a?(Vec3) #dot product
                return @x*a.x + @y*a.y + @z*a.z
            end
        end
    
        def coerce(other)
            return self, other
        end
    end
    

    if you define v as v = Vec3.new then the following will work: v * 5 and 5 * v The first element returned by coerce (self) becomes the new receiver for the operation, and the second element (other) becomes the parameter, so 5 * v is exactly equivalent to v * 5

提交回复
热议问题