First, your Sum class is invalid. The definition should be.
class Sum
def initialize(a, b)
@x = a + b
end
end
By default, the method called to get a human readable representation is inspect. Try this in irb
$ s = Sum.new(3, 4)
# => #<Sum:0x10041e7a8 @x=7>
$ s.inspect
# => "#<Sum:0x10041e7a8 @x=7>"
But in your case, you use the puts
method which forces a string conversion. For this reason, the Sum
object is first converted to string using the to_s
method.
$ s = Sum.new(3, 4)
# => #<Sum:0x10041e7a8 @x=7>
$ puts s
# => #<Sum:0x10041e7a8>
$ puts s.to_s
# => #<Sum:0x10041e7a8>
Also note your last example fall into a third case. Because you sum a Fixnum + an other object, the result is expected to be a Fixnum and the method called is to_s
but the one defined in the Fixnum class.
In order to use the one in your Sum class, you need to switch the items in the sum and define the +
in your object.
class Sum
def initialize(a, b)
@x = a + b
end
def +(other)
@x + other
end
def to_s
@x.to_s
end
end
s = Sum.new(3, 4)
s + 10
puts s
# => 17