From: Gavin Sinclair Date: 2003-12-01T22:48:08+09:00 Subject: Re: class << x On Sunday, November 30, 2003, 7:02:41 PM, Joel wrote: > The 'class << x' notation has some weaknesses: > * It looks a bit like a heredoc, but there is no analogy. Never thought of that. > * '<<' does not have any other role as an operator or special form > associated with singleton classes. No, but one's enough. How many operators associated with singleton classes do you want? > * '<<' suggests an append or shift operation, or perhaps a "much less > than" comparison, or even some kind of bracket ('<>') notation. This is where the analogy holds reasonalby well for me. I see it as some class derived from 'x'. > * It looks too much like 'class Y < x' in which the new class Y is less > than x in the ancestral sense. However, the analogy is false--there is > no class below x. I'm not sure about that. Isn't there an anonymous class that's roughly interpreted as "the singleton class of x"? > * How do you read it? "class under x"? "class singleton of x"? "Class under x" is good enough for me. However, I don't tend to read it as anything, rather "class << x" appears as a single token in my mind :) > It has bothered me for the last 3 years, but I simply accept it as an > idiom and get on with life. We don't always have to construct meaning > for the symbols we push around. That's the key, really. Before Ruby, I'd never heard of singleton methods on an object. If the concept is unfamiliar, as I suspect it is to many people, then it's asking a bit much for the symbol to communicate the meaning. That's why I hold that it's just something people have to learn about Ruby, and that's all there is to it. > Still, I'd feel better if there were some method on objects that > returned the singleton class and you could use that in a class > definition, something like this: > def singleton(x); class << x; self; end; end In extensions.rubyforge.org, I included Object#singleton_class, with the documentation: Returns the singleton class associated with this object. How useful this is I don�t know, but it�s an idiom that has appeared on ruby-talk several times. :) > x = [0,1,2,3] > # class singleton(x); end # parse error! > singleton(x).class_eval do > def last_elt; at(-1); end > end > p x.last_elt # ==> 3 > But this is a poor workaround, since do..end and class..end have > different scoping rules. It's also poor because it mandates the use of eval, IMO. Thanks for the interesting tour! Gavin