How to implicitly convert custom class to integer in Ruby?
implicit-conversion, ruby
Solution
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.
Problem
I have the following class: ``` class Register attr_accessor :val def initialize @val = 0 end end ``` I wish to be able to, given `ax=Register.new`, type `3 + ax` or `ax + 3` and get as a result the equivalent of `3 + ax.val`. I tried searching but can't find how this is done in Ruby.