ruby operator overloading question -


I am walking with Ruby and Open for entertaining purposes, and I have to write some 3D vector / plain / etc Decided to make classes some maths beautiful

Simple example:

  class Vec3 attr_accessor: x ,: y ,: z def * (a) if a.is_a? (Numerical) scalar return Vec3.new (@x * a, @ y * a, @ z * a) alsf a.is_a (Vec3) #dot product return @ x * ax + @ y * ay + @ z * az end End end v1 = vec3.new (1,1,1) v2 = v1 * 5 #produces [5,5,5]  

All that is fine and dandy, but I also write I want to be enabled

  v2 = 5 * v1  

for which FixName or float or whatever functionality is required to add, but I can not Find out how to overload or expand multiplier without completely transferring it Is it possible in Ruby?

"text">

Using a monkey, monkey- Better method than patching is:

  class Vec3 attr_accessor: x ,: y ,: z def * (a) if any .is_a? (Numerical) scalar return Vec3.new (@x * a, @ y * a, @ z * a) alsf a.is_a? (Vec3) #dot Product Return @ x * ax + @ y * If you define v as  v = Vec3.new , then the following:  AE + @ z * Age End End DEF CORUS (other) returns self, other end and  

will work: v * 5 and 5 * v back for the first time A new receiver is created for the (self) operation, and the second element becomes (other) parameter, so 5 * v exactly v * 5


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

php - jQuery AJAX Post not working -