For ax + 3
to work, you need to define +
method on your class:
def +(other)
@value + other
end
However, 3 + x
will still result in an error as the interpreter won't have clue how to combine a Fixnum
with the instance of your class. To fix this, define the coerce
method like this:
def coerce(other)
if other.is_a?(Fixnum)
[other, @value]
else
super
end
end
I won't go into detail on how coerce
works as we already have a great answer here.