Binary operators, coerce, and non numeric types

okay, i understand how to define a coerce method, but i don’t think it
can do what i want, in fact i think the only way to do what i want is
rather ugly unless i drill down and actually patch the interpreter.

class X
def + other
BinOp.new(self,other,:+)
end
end

class BinOp
def initialize x,y,op
@x,@y,@op=x,y,op
end
end

x = X.new

x + x # -> BinOp, the behaviour i want
x + 3 # -> BinOp, the behaviour i want
3 + 3 # -> 6, the behaviour i want
3 + x # is of courses an error, but i want it to return a BinOp

the only way i can find that ruby will support this, is by writing

class Fixnum
alias old_add +
def + other
if other.kind_of? X
BinOp.new self, other, :+
else
self.old_add other
end
end
end

which is pretty ugly considering i have many operators to support, as
well as several numeric types. of course i could automate it with some
metaprogramming, but i’d like to know if anyone has any better ideas?

ok i hadn’t fully grokked coerce, and have found a solution. just incase
anybody is interested:

class X

def + other
bin_op other, :+
end
def ** other
bin_op other, :**
end
def - other
bin_op other, :-
end
def / other
bin_op other, :confused:
end

def bin_op other, op
if @coerced
@coerced = false
BinOp.new other, self, op
else
BinOp.new self, other, op
end
end

def coerce other
@coerced = true
[self,other]
end

end

class BinOp
def initialize x,y,op
@x, @y, @op = x, y, op
end
def to_s
“BinOp #@x #@op #@y
end
end

x = X.new

puts x + 3
puts 3.0 + x
puts 2 - x
puts x - 10
puts 23 ** x
puts 2.99 / x
puts x / -1

cheers,
_c

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs