On Thursday, June 12, 2003, at 07:26 PM, you CAN teach an old dog ... 
wrote:

> I wish to control the default display of my objects, and thought to_s
> would be the right hook. But ruby (at least irb) seems to use my to_s
> only if the class has no instance variables. Am I doing something
> wrong?
>
> What other display-related hooks are there?
>
> Thanks
>
> irb> class A
> irb>   def to_s
> irb>     "an A"
> irb>   end
> irb> end
> nil
>
> irb> A.new
> an A          # uses to_s
>
> irb> class B
> irb>   def initialize(x)
> irb>     @x = x
> irb>   end
> irb>   def to_s
> irb>     "a B"
> irb>   end
> irb> end
> nil
>
> irb> B.new (5)
> #<B:0x2a51b98 @x=5>   # ignores to_s

irb just shows what the input expression returns. The things you see 
after each line are just string representations of what Ruby would 
return internally if run in a program.

In 'A', your object only contains a method, so Ruby just returns the 
result of invoking the method. I think the reason for this is that that 
is all you asked the class to do.

In 'B', your object contains data values when initialized, so Ruby 
returns the object (irb represents this by showing the result of [the 
object].inspect). In a program the object would be available to be used 
for further purposes (although you will likely want or need (if you're 
not chaining a bunch of methods) to assign it to a variable so that you 
can reference it subsequently in your program.

To display the result of the to_s method in 'B' you would need to call 
it:

B.new(5).to_s

If you assign a new object to a variable, you can always show the name 
of the class by writing:

b = B.new(5)
puts b.class

I'm sure there are nuances I'm missing, but the above is my 
understanding so far of what's going on with irb and to_s.