On Wed, May 12, 2010 at 12:16 PM, Colin B.

[email protected] wrote:

it won’t end up with the arguments backwards.

and if <=> is defined for (a representation of) other and

(a representation of) self, that probably won’t work either!

Based on an earlier thread from the OP where the use case was

operations on integers and points, he might be concerned about my

pointing out (no pun intended) that, as far as I know, while there’s a

conventional meaning for multiplying a vector quantity (like a Point)

and a scalar quantity (like an Integer), there isn’t for adding or

subtracting a scalar and a vector.

So we need to allow

1 * Point.new(1,1)

but disallow

1 + Point.new(1, 1)

or

1 - Point.new(1,1)

One way to address this might be something like

class Point

attribute :x, :y

def initialize(x, y)

self.x, self.y = x, y

end

def +(value)

if Point === value

Point.new(x + value.x, y + value.y)

else

raise ArgumentError.new(“Attempt to add a point to a scalar”)

end

end

def -(value)

if Point === value

Point.new(x + value.x, y + value.y)

else

raise ArgumentError.new(“Attempt to subtract a point from a

scalar”)

end

end

def dot_product(other_point)

x*other_point.x + y * other_point.y

end

def *(value)*

if Point == value

dot_product(value)

else

Point.new(xvalue, y*value)

end

end

class ScalarWrapper

attribute :scalar_value

```
def initialize(scalar_value)
self.scalar_value = scalar_value
end
def +(value)
raise ArgumentError.new("Attempt to add scalar to a point")
end
def -(value)
raise ArgumentError.new("Attempt to subtract a scalar from a
```

point")

end

```
def *(other_point)
Point.new(scalar_value*other_point.x,
```

scalar_value*other_point.x)

end

end

end

def coerce(other)

[Point::ScalarWrapper.new(other), self]

end

end

–

Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/

Github: rubyredrick (Rick DeNatale) · GitHub

Twitter: @RickDeNatale

WWR: http://www.workingwithrails.com/person/9021-rick-denatale

LinkedIn: http://www.linkedin.com/in/rickdenatale