문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top