On Aug 26, 2005, at 10:03 AM, Mark Volkmann wrote:

> Here's what I've learned so far.
> 1) Every object has to_s because Object provides a default  
> implementation.
> 2) Some classes override to_s to return a more useful String.
> 3) to_str should only be implemented in classes whose objects can
> logically be used as Strings.
>
> If you're going to implement to_str in a class, is there a reason why
> it might return something different than to_s?  Is one considered a
> human-readable representation and the other something else?

I think every time I've implemented to_str (rare for me) it just  
called to_s, yes, though it's clear others differ on this.

To me, the functionality of the methods isn't what differs so much,  
it's when they're called.  A call to to_s means (to me), convert this  
object to a String.  The more implicit to_str is me telling Ruby,  
this object behaves as a String.

Ruby seems to back that idea up too:

irb(main):001:0> class A
irb(main):002:1> def to_s; "converted"; end
irb(main):003:1> end
=> nil
irb(main):004:0> class B
irb(main):005:1> def to_str; "behaves as"; end
irb(main):006:1> end
=> nil
irb(main):007:0> "A String:  " + A.new
TypeError: cannot convert A into String
         from (irb):7:in `+'
         from (irb):7
         from :0
irb(main):008:0> "A String:  " + B.new
=> "A String:  behaves as"

> Isn't "can be logically used as Strings" a somewhat subjective thing?

Clearly it is, yes.

James Edward Gray II