to_s and to_str

M

Mark Volkmann

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?

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

--=20
R. Mark Volkmann
Partner, Object Computing, Inc.
 
J

James Edward Gray II

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top