On 11/19/05, Robert Klemme <bob.news / gmx.net> wrote:
> > For many of the other core classes (and definitely all other immediate
> > classes), #inspect returns a representation that is eval'able to get
> > back an equivalent (or the same) object.  When possible, I think that
> > is what #inspect should do.  I think it is a bug that Symbol#inspect
> > almost does it, but not quite (quotes some cases but not others).
>
> Although I'd agree that Symbol#inspect can be improved and should be
> changend (as it's an easy fix) I have a different opinion about the usage of
> inspect in general: even inspect methods of core classes fail to return
> something that is proper ruby code.
>
> $ ruby -e 'p Object.new'
> #<Object:0x100f6b28>
> $ ruby -e 'a=[1];a<<a;p a'
> [1, [...]]

I didn't say all core classes return something evalable for #inspect
(I said many).  Here's the list I see:

FalseClass, TrueClass, NilClass
Fixnum, Bignum
Float
String
Regexp
Symbol - close but no cigar
Class - kind of - it returns a constant for class that can be evaled
Array, Hash, Range - if no recursion and all elements have an evalable #inspect

> > I found this problem when doing code generation.  For immediate
> > objects, I embedded the value in the code directly by using #inspect.
> > I had to put in a hack for Symbol because of the problem discussed.
>
> IMHO relying on #inspect for code generation is inappropriate.  As the rdoc
> of Object#inspect indicates it's meant to yield a human readable
> representation.  If you want to generate code you should use another
> mechanism.  For example, you can define a separate method (even if it calls
> #inspect as default implementation).  Or you use YAML / Marshal for complex
> data structures.

Notice I said only immediate objects.  This was actually only an
optimization.  For non-immediate objects, I'm putting them in an
instance variable to be accessed by the generated code.  For immediate
objects there was no reason for this as they were immutable and had no
object creation overhead.  Depending on the instance variable usage
overhead vs. object creation overhead, I might do the same for Float
and other immutable, evalable #inspect classes.  Again, this is only
an optimization - handling some classes differently doesn't change the
functionality.