The problem is that 6 - Roman.new(1)
is the same as 6.-(Roman.new(1))
i.e. it is calling the built in subtraction method of Fixnum
. Since Fixnum
doesn't know about your Roman
class, this calls your coerce
method.
But you defined coerce
to return a Fixnum in this case! The solution is to coerce the other operand, rather than self
.
def coerce other
[self.class.new(other), self]
end
But if you try this with your code, you'll get a stack error! That's because it's now coercing both operands into instances of Roman
and it still doesn't know how to subtract them. You should redefine your subtraction method to handle those cases.
attr_reader :number
def - n
return Roman.new(@number - n.number) if n.is_a? Roman
Roman.new(@number - n)
end