From: Robert Klemme Date: 2004-12-02T19:12:43+09:00 Subject: Re: singleton methods : when are they not permitted? "itsme213" schrieb im Newsbeitrag news:u_mrd.59121$KQ2.55810@fe2.texas.rr.com... > > > > Have I not defined a singleton method on a literal? > > > > You have not. You defined a singleton method on a string instance that > > represents the sequence "x". If you like you can view it that way that > > the literal "x" is not directly accessible. It just creates a string > > instance with sequence "x" every time it is evaluated: > > Ah. Subtle. Thanks (assuming I've got it!). Would this re-phrasing be the > right idea? > > A literal (I'll use the term 'value' object as a generalization) is a > virtual object that you cannot access or manipulate. Every conceivable value > object already exists before the first line of your code is run. What you > can create, access, and manipulate are instances that represent, by various > encodings, references to a given value object. I prefer to view a literal as a special kind of expression that yields an instance on each execution. Whether this is always the same instance (as for symbols, Fixnum and surprisingly also for Bignum and Regexp) or whether it's a different instance (as for strings, arrays and hashes) depends on the literal. > For immediate objects, these referencing instances use encodings that > directly share the same object_id. > e.g. > :a # reference to unique virtual symbol :a > :a.object_id == :a.object_id #=> true > :a == :a #=> true, obviously > > For all other value objects, those referencing instances have "==" defined > so that references to the same value object compare as identical. > "x" # reference to unique virtual string "x" > "x".object_id == "x".object_id #=> false > "x" == "x" #=> true I think you got it. I was just irritated by you usage of "encoding" as I associate this usually with character encodings such as ISO-8859, UTF-8, UTF-16 and the like. The crucial part is to be aware of the fact that there might or might not be instances created and that this has performance implications. That's why I usually define class constants for certain strings like this class Foo BAR = "foo".freeze def doit(x) if BAR == x "yes" else "no" end end end Kind regards robert