Charles Mills
11/30/2004 5:07:00 PM
On Nov 30, 2004, at 5:08 AM, David A. Black wrote:
> Hi --
>
> On Tue, 30 Nov 2004, Giulio Piancastelli wrote:
>
>> Florian Gross wrote:
>>
>>> itsme213 wrote:
>>>> Are to_s, inspect, etc. defined more-or-less consistently for the
>> library
>>>> classes? Are they used consistently by the various tools like irb,
>> debug,
>>>> test/unit, breakpoint, etc?
>>>
>>> .inspect is usually used for debug purposes and .to_s for end-user
>>> purposes.
>>
>> So, why does [1,2,3].to_s give '123' and [1,2,3].inspect give '[1, 2,
>> 3]' as answers? Not a really end-user answer, the one given by
>> Array#to_s, isn't it? The inspect method here is much more end-user
>> oriented: why is that?
>
> I think it's probably because the '123' form is conceivably useful
> once in a while as a string, whereas '[1,2,3]' probably isn't. Also,
> #inspect sort of has to return something other than '123', so having
> #to_s also return that would just duplicate that functionality.
>
Array#to_s is essentially Array#join with no args... irb uses #inspect
to display the result of each statement. It is a bit annoying when you
have highly nested objects and/or objects with lots of instance
variables that give you about a page and a half of output when inspect
is called. I guess if you know your class is going to be like that is
may be useful to define inspect something like the following:
###
def inspect()
"#<#{self.class}: #{@very_important_ivar}>"
end
###
Opinions may differ though...
-Charlie