views:

63

answers:

2

Assume, I have an object x of MyClass. What method is called, when I do puts x? I need to override it with my own one.

I thought it was .inspect, but somehow overridden inspect isn't being called.

For example, I have a class Sum:

class Sum
  initiazlie a, b
     @x = a + b
  end
end

And I wanna access the result like this:

s = Sum.new(3,4)
puts s         #=>    7   How do I do this?
puts 10 + s    #=>   17   or even this...?
+4  A: 

It calls: to_s

class Sum
  def to_s
    "foobar"
  end
end

puts Sum.new #=> 'foobar'

Or if you want, you can just call inspect from to_s, so that you have a consistent string representation of your object.

class Sum
  def to_s
    inspect
  end
end
Squeegy
+3  A: 

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
Simone Carletti