Question

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.

Was it helpful?

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.

OTHER TIPS

You can add the method to the class:

class Register
  attr_accessor :val
  def initialize
    @val = 0
  end

  def +(x)
    @val + x
  end
end

a = Register.new
a + 5 # => 5

Note that, this method will allow you to call a + 5 but not 5 + a. You will get a TypeError: Register can't be coerced into Fixnum if you try.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top