Hi! When I read the Ruby manual, I noticed that for class Array, there are class methods and instance methods. Class methods: [] and new instance methods: too many (not list here) My question is: what's this class methods? I remember in C++, all methods should be instance level, right? Thanks! Yours, Hank
on 2005-12-08 07:32
on 2005-12-08 07:40
On Dec 8, 2005, at 1:30 AM, Hank Gong wrote: > My question is: what's this class methods? I remember in C++, all > methods > should be instance level, right? > Thanks! > > Yours, Hank class methods are (more or less) the same thing as static methods in C ++. eg. class A { public: static int aClassMethod { return 42; } int anInstanceMethod { return 7; } }; A::aClassMethod( ); //=> returns 42 A x; x.anInstanceMethod( ); //=> returns 7
on 2005-12-08 07:52
Hank Gong wrote:
> should be instance level, right?
p Array.class # Class
p Array.instance_of? Class # true
Array is an instance of Class, so those methods are, in a way, instance
methods.
No?
They're not eigenmethods are they?
:)
James
--
http://www.ruby-doc.org - Ruby Help & Documentation
http://www.artima.com/rubycs/ - Ruby Code & Style: Writers wanted
http://www.rubystuff.com - The Ruby Store for Ruby Stuff
http://www.jamesbritt.com - Playing with Better Toys
http://www.30secondrule.com - Building Better Tools
on 2005-12-08 08:00
In Ruby a class is an object too. So it can have it's own methods just
like any other object. There methods are different from a class
instance methods, which are the ones that define the nature of an
object instantiated from the class. So lets say we have a class:
class MyClass
end
Then we can treat is like any other object and send messages to it.
MyClass.object_id #=> -606921464
That's what is called a *class method*. Also, you may have noticed that
you can define a method tailored specifically for any object. For
instance:
a = "hi"
def a.up
self.upcase
end
a.up #=> "HI"
Class methods are actually the same thing. You can create one of these
tailor-made methods for a class likewise:
def MyClass.upname
name.upcase
end
MyClass.upname #=> "MYCLASS"
HTH,
T.
(Hey all, I didn't use the term adhoc! See I can take a hin... I mean a
brick to the head ;-)
on 2005-12-08 15:35
Sorry Hank, if you are unware of what were talking about in these last two posts. We're refering to a very recent thread that discussed what to call these type of methods. Presently they are known a "singleton methods", but becuase of the clash with what is known in OOP generally as the *singleton pattern*, there is on-going discussion on finding a better term. Recent alternative suggestions are "eigen" and "adhoc". T.
on 2005-12-08 19:31
I carefully read two articles about classmethods and singleton concept. Now for me, the concept of classmethods seems not difficult for me now. It's just singleton methods for a class because class is also a object. However, the concept of singleton still not clear for me, also how to use them is also not making sense for me. Yours, Hank
on 2005-12-08 20:03
Hi -- On Fri, 9 Dec 2005, Hank Gong wrote: > I carefully read two articles about classmethods and singleton concept. > Now for me, the concept of classmethods seems not difficult for me now. It's > just singleton methods for a class because class is also a object. > However, the concept of singleton still not clear for me, also how to use > them is also not making sense for me. > Basically an object's singleton class is a class created ad hoc, and in a sense retroactively, for the sole purpose of being the-class-where-this-object's-singleton-methods are defined and live. David P.S. Aside to Tom S.: I agree it's ad hoc in the sense of being for a specific purpose, but I'm not sure I agree that it's ad hoc where the "hoc" (actually the "hic", I guess, in the nominative case :-) is the object itself. One then runs into questions like: are instance variables "ad hoc" variables? etc. -- David A. Black dblack@wobblini.net "Ruby for Rails", forthcoming from Manning Publications, April 2006!
on 2005-12-08 21:05
dblack@wobblini.net wrote: > P.S. Aside to Tom S.: I agree it's ad hoc in the sense of being for a > specific purpose, but I'm not sure I agree that it's ad hoc where the > "hoc" (actually the "hic", I guess, in the nominative case :-) is the > object itself. One then runs into questions like: are instance > variables "ad hoc" variables? etc. Interesting. Perhaps we've met halfway then. 'Ad hoc' is an excellent discriptive term, but in trying it on for size some more, so to speak, I'm not as certain that it makes a good *techncal* term, not because of negative conotations, but because it may be too generic, much like 'meta'. Which I think it is what you're pointing out here. Of course, this might be a problem with any term that doesn't already have a fitting techincal meaning. T.
on 2005-12-08 21:44
transfire wrote: > dblack@wobblini.net wrote: >> P.S. Aside to Tom S.: I agree it's ad hoc in the sense of being for a >> specific purpose, but I'm not sure I agree that it's ad hoc where the >> "hoc" (actually the "hic", I guess, in the nominative case :-) is the >> object itself. One then runs into questions like: are instance >> variables "ad hoc" variables? etc. > > Interesting. Perhaps we've met halfway then. 'Ad hoc' is an excellent > discriptive term, but in trying it on for size some more, so to speak, > I'm not as certain that it makes a good *techncal* term, not because of > negative conotations, but because it may be too generic, much like > 'meta'. Which I think it is what you're pointing out here. Of course, > this might be a problem with any term that doesn't already have a > fitting techincal meaning. > > T. What did you guys think about using simpleton to refer to these methods/classes? That way there can be differentiation between a class which was made single by 'include singleton' (that is, has one single instance somewhere) and a class which is made single (or simple) by having only class methods and class data. The one which is an instance of the design pattern could be called 'singleton' (since it isn't the one in question anyway) and the other could be called 'simpleton'. --J
on 2005-12-08 23:04
On Dec 8, 2005, at 3:45 PM, jonathan <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> wrote: > What did you guys think about using simpleton to refer to these > methods/classes? I'd vote no on that name regardless. If you think 'ad hoc' has negative connotations... > That way there can be differentiation between a class > which was made single by 'include singleton' (that is, has one single > instance somewhere) and a class which is made single (or simple) by > having only class methods and class data. Are you confusing a class that has no instances (yet) with the class returned by the expression (class <<obj; self; end) ? I don't see anything particularly special or interesting about a class with no instances (I *think* that is what you mean by a class with 'only class methods and class data'). Certainly that isn't what all the hubbub has been about regarding 'meta/eigen/singleton/shadow'. Gary Wright
on 2005-12-08 23:57
On 12/8/05, dblack@wobblini.net <dblack@wobblini.net> wrote: > I'm not sure I agree that it's ad hoc where the > "hoc" (actually the "hic", I guess, in the nominative case :-) is the > object itself. Heu magister carbunculi! ;) Ridens magna voce Iohannes
on 2005-12-09 07:15
> > Are you confusing a class that has no instances (yet) with the class > returned by the expression (class <<obj; self; end) ? > I don't think so. The expression you wrote is an example of what has been called a singleton but, it has no methods at all (neither class nor instance). > I don't see anything particularly special or interesting about a class > with no instances (I *think* that is what you mean by a class > with 'only class methods and class data'). Certainly that isn't what > all the hubbub has been about regarding 'meta/eigen/singleton/shadow'. > I got the impression from the other thread on this that this is what the hubbub is about. Given a class that allows one instance to be instantiated, some optional class data members, some instance data members, and some class methods and instance methods and another class that allows only class data and class methods, there is no difference *in essence*. The argument was what to call the second sort of class. So, in other words, the difference between these two classes is really the fact that you can refer to some data in the first type as instance data, but since there's only one instance, that's really no different than class data (except for syntax of course). In essence, these two types of classes are the same and therefore matz's original corrected term for the second type 'singleton' fits. But, it is easily confused with the 'true' singleton which is an instance of the design pattern singleton (and the first class described above). However, to eliminate ambiguity between the two, we need a term for the second type of class (which is called a 'static class' in c# or c++, but can't be in ruby because it is a dynamic language). My proposal of simpleton is really arbitrary--either class could be singleton and the other simpleton, but since more would have to be changed to make the first type simpleton, i suggested the second. And, however much dislike you have for 'simpleton' it is accepted as a synonym for singleton. I do understand of course, that enforcing such a subtle difference in terminology is impossible and agree with the other posters that there is most likely going to be umpteen different ways of referring to these classes (and methods). I should also put a disclaimer on everything I just said above which could be totally off base: I'm coming from a 'compiled' bkg and this commentary might not make sense in an interpreted world. I do want to be corrected if I'm totally off-base with this, so please enlighten me. Nevertheless, even my misunderstandings should prove useful to someone. :) --J
on 2005-12-09 07:38
My understanding of 'singleton' methods or 'ad hoc' methods or
'eigenmethods' or classes of each of these came from this post (by
transfire):
> (you can call methods of a module without mixing it in right?)
Yes, if they are "module methods" as opposed to instance methods.
Modules methods, (also called class methods but usually in the context
of class) are singleton methods, or adhoc methods (my new prefered
term). You can tell this by the way they are defined --the name of the
object proceeds the method name in the def statement (eg. 'def
ImageBob.get_blob'). Another way to write them:
module ImageBlob
class << self # opens adhoc context
def get_blob
...
end
end
end
T.
So, a class with only 'ad hoc' methods would be an 'ad hoc' class or
singleton, or eigen or static or whatever term you choose.
Hope this helps to get us back on the same page.
--J
on 2005-12-09 14:58
J, I think the static class idea has thrown you off a bit. Not that I'm an expert on C#, but from what I've read it looks like a static class is how one implements the singleton _pattern_ in C#. While Ruby has singleton.rb with its Singleton mixin to do this kind of thing, it's not nearly as useful b/c one can also use a module and its "singleton class" (i.e. adhoc/eigenclass) to get much of the same effect. The irony here, is though they can overlap in usage the later is actually quite different and has more uses. So forget about the C# stuff for a moment and have a read of this page, http://rubygarden.org/ruby?SingletonTutorial That should clarify things for you. T.
on 2005-12-10 03:59
transfire wrote: > I think the static class idea has thrown you off a bit. Not that I'm an > expert on C#, but from what I've read it looks like a static class is > how one implements the singleton _pattern_ in C#. Well, actually, I think you do it the same way you would in C++, i.e., you have a static data member that is the ptr to the one instance (starting out as NULL) and the first time the constructor is called, you init it, and everytime after that, return the instance ptr. (There are other ways involving private constructors)). Though, my discussion above points out how, in essence, a static class is a singleton class (barring syntax differences). The only reason I had this static class == singleton equivalence in my head was due to the actual example we were dealing with which was a class with two singleton methods (and no other methods or instance data members). So, a class which contains only singleton methods would not be considered a singleton class? > While Ruby has > singleton.rb with its Singleton mixin to do this kind of thing, it's > not nearly as useful b/c one can also use a module and its "singleton > class" (i.e. adhoc/eigenclass) to get much of the same effect. The > irony here, is though they can overlap in usage the later is actually > quite different and has more uses. > > So forget about the C# stuff for a moment and have a read of this page, > > http://rubygarden.org/ruby?SingletonTutorial > Thanks for the link. Yea, that does look like some powerful stuff. Seems to me that this sort of singleton (using the >> syntax) could be known as a 'singleton subclass' or a 'singleton extension.' Any given class can have infinitely many singleton subclases, no? --J
on 2005-12-10 04:11
T, > Any given > class can have infinitely many singleton subclases, no? Oops. This statement from the page you linked to seems to answer that question: If 'a' already has a singleton class then any more singleton methods you define are just added to it. Does this mean that a class can have only one singleton subclass and that all methods added anywhere in the program are added to that single instance? If so, I wonder why this is. It seems to me to be more useful if you can have infinitely many singleton subclasses. I suppose you still can have divergence of this sort with individual instances, but why not with the class itself? --J
on 2005-12-10 04:54
jonathan leonard <zjll9@imail.etsu.edu> wrote: > > Does this mean that a class can have only one singleton subclass and > that all methods added anywhere in the program are added to that single > instance? If so, I wonder why this is. It seems to me to be more > useful if you can have infinitely many singleton subclasses. I suppose > you still can have divergence of this sort with individual instances, > but why not with the class itself? Well, I think its basically because Matz used the class nothing more then an easy way to implement ad hoc methods. It was the methods that mattered to him, not the class --the class was just a vehicle. He's talked about the possibility of not utilizing the class in the future. I assume that means these methods would then just exit in a separate underlying namespace of the class, as opposed to a separate class altogether. Which may also be the reason he's allowed then name to remain a bit amorphis and never provided a convenience method for accessing it. T.
on 2005-12-10 05:22
On Sat, 10 Dec 2005, Trans wrote: >> If 'a' already has a singleton class then any more singleton methods you > then an easy way to implement ad hoc methods. It was the methods that > mattered to him, not the class --the class was just a vehicle. He's > talked about the possibility of not utilizing the class in the future. > I assume that means these methods would then just exit in a separate > underlying namespace of the class, as opposed to a separate class > altogether. Which may also be the reason he's allowed then name to > remain a bit amorphis and never provided a convenience method for > accessing it. The latter, yes, from what Matz has said (no convenience method because it may not be a class in the future). The former -- amorphous name -- no: I am using the term "singleton class", and I will use it until we find the better term as I said in [ruby-talk:141548] 7 months ago in the famous Ilias thread. That sounds pretty non-amorphous :-) But the whole thing may indeed become non-class-based. I'm not sure what that would entail. I kind of think that if it were something other than a class, one would end up longing for a "class interface" to it, and then it might as well be a class.... David -- David A. Black dblack@wobblini.net "Ruby for Rails", forthcoming from Manning Publications, April 2006!
on 2005-12-10 07:53
transfire wrote: > Well, I think its basically because Matz used the class nothing more > then an easy way to implement ad hoc methods. It was the methods that > mattered to him, not the class --the class was just a vehicle. He's > talked about the possibility of not utilizing the class in the future. > I assume that means these methods would then just exit in a separate > underlying namespace of the class, as opposed to a separate class > altogether. Which may also be the reason he's allowed then name to > remain a bit amorphis and never provided a convenience method for > accessing it. Hmm.. Ok. But, with Ruby, you can still dynamically create subclasses that aren't singletons and extend them as well as instanciate instances of them, right? That would provide the flexibility I was referring to above, but I suppose it would require typing quite a few more characters. So do I understand correctly that Matz designed the whole singleton creation mechanism ( << ) as a shorthand for doing more long-winded dynamic creation/enhancing? --J BTW, I haven't said so explicitly yet (but it might be gathered from other posts) that I think Ruby is a very cool language. I've always had an interest in self-modifying code and of the langs I've studied so far, Ruby makes it the most sane. Of course, we aren't supposed to be doing that stuff anyway. :) (makes it too hard for readers/maintainers to understand).
on 2005-12-10 15:30
Hi -- On Sat, 10 Dec 2005, jonathan <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> wrote: > > Hmm.. Ok. But, with Ruby, you can still dynamically create subclasses > that aren't singletons and extend them as well as instanciate instances > of them, right? That would provide the flexibility I was referring to > above, but I suppose it would require typing quite a few more > characters. So do I understand correctly that Matz designed the whole > singleton creation mechanism ( << ) as a shorthand for doing more > long-winded dynamic creation/enhancing? The starting-point of the whole thing is the principle that objects can be individually extended. Two instances of MyClass, for example, begin life with the same capabilities (methods), but during their lives can diverge: class MyClass end a = MyClass.new b = MyClass.new def a.x end def b.y end The singleton class mechanism is just a way to store those "extra" methods. The methods written for a (namely, "x") go in a's singleton class; those for b, in b's; etc. These classes are created automatically when they are needed. If you want to open a class definition block for an object's singleton class, you use the class keyword, plus "<< obj". This special syntax is necessary because singleton classes are anonymous. Other than that, it's very much like doing "class C". It's all very simple and elegant, isn't it? :-) David -- David A. Black dblack@wobblini.net "Ruby for Rails", forthcoming from Manning Publications, April 2006!
on 2005-12-11 02:34
dblack wrote: >> Hmm.. Ok. But, with Ruby, you can still dynamically create subclasses >> that aren't singletons and extend them as well as instanciate instances >> of them, right? That would provide the flexibility I was referring to >> above, but I suppose it would require typing quite a few more >> characters. So do I understand correctly that Matz designed the whole >> singleton creation mechanism ( << ) as a shorthand for doing more >> long-winded dynamic creation/enhancing? > > The starting-point of the whole thing is the principle that objects > can be individually extended. Two instances of MyClass, for example, > begin life with the same capabilities (methods), but during their > lives can diverge: > > class MyClass > end > > a = MyClass.new > b = MyClass.new > > def a.x > end > > def b.y > end > > The singleton class mechanism is just a way to store those "extra" > methods. The methods written for a (namely, "x") go in a's singleton > class; those for b, in b's; etc. These classes are created > automatically when they are needed. Hmm. Ok, so there really is no singleton class for Myclass? In other words, must the singleton always be associated with an instance and not a class? > > If you want to open a class definition block for an object's singleton > class, you use the class keyword, plus "<< obj". This special syntax > is necessary because singleton classes are anonymous. Other than > that, it's very much like doing "class C". > > It's all very simple and elegant, isn't it? :-) > Yea. That is cool, but can you still do something like this: class Myclass end def extend_class( some_class ) code = %{ class #{some_class.class}_extension < #{some_class.class} def new_method1 end ... end } eval( code ) extend_class( Myclass ) x = Myclass_extension.new x.new_method1 y = Myclass_extension.new y.new_method1 Some variation of this (where the extended class is named uniquely) should allow infinitely many extended subclasses and also allow non-singleton (i.e., many) instances of the subclasses. Of course, I suppose you could start with x and y as instances of the base class and add the new_method's to each of them just as easily (and with probably less typing). So, would there ever be a reason to do something like I wrote above? --J
on 2005-12-11 05:06
On Dec 10, 2005, at 8:34 PM, jonathan wrote: > Hmm. Ok, so there really is no singleton class for Myclass? In other > words, must the singleton always be associated with an instance and > not > a class? In Ruby, a class *is* an instance. Specifically, a class is an instance of the class Class. So, yes, you can reference the singleton object of a class: class <<Array end More often it is done like this though: class Array class <<self # instance methods defined here will be # for the object Array (which happens to be a class) # so these methods become 'class methods' for Array end end Alternatively you can do it like this: def Array.class_method1 # an instance specific method # in this case the instance is the class object Array end > end } > eval( code ) > > extend_class( Myclass ) > x = Myclass_extension.new > x.new_method1 > y = Myclass_extension.new > y.new_method1 I'm not sure what you are getting at here. Myclass.class is the particular object Class. Because all class objects are instances of Class. #{some_class.class}_extension ends up being the string Class_extension because Class.to_s is the string 'Class'. If you want to subclass and add methods just do it: class Myclass end class Subclass < Myclass def new_method1 end end x = Subclass.new y = Subclass.new x.new_method1 y.new_method1
on 2005-12-11 06:07
gwtmp01 wrote: >> >> extend_class( Myclass ) >> x = Myclass_extension.new >> x.new_method1 >> y = Myclass_extension.new >> y.new_method1 > > I'm not sure what you are getting at here. > > Myclass.class is the particular object Class. Because > all class objects are instances of Class. > > #{some_class.class}_extension > > ends up being the string > > Class_extension > > because Class.to_s is the string 'Class'. > Oops. It should have been #{some_class}. The whole point of that was so that I could have code that writes code (dynamically) based on states of other parts of the program (I think it is also known as metaprogramming). Of course, with that simple example I posted, it wouldn't make much sense. It seems like this sort of thing would be very useful for artificial intelligence (i.e., learning). On the class singleton example you posted: that's very neat. Now, I think my understanding of these sort of singletons is complete. :) --J
on 2005-12-11 06:11
On 2005.12.11 10:34, "jonathan <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu>" <zjll9@imail.etsu.edu> wrote: > > can be individually extended. Two instances of MyClass, for example, > > end > words, must the singleton always be associated with an instance and not > > end } > non-singleton (i.e., many) instances of the subclasses. Typically, if I understand you correctly, you could just use this idiom (unless you want to just eval the whole thing): # Classes are constants # | Inherit MyClass # | | We can use blocks # | | | # V V V MyClassExtension = Class.new(MyClass) { def self.some_method() # ... end def some_method() # ... end } > Of course, I suppose you could start with x and y as instances of the > base class and add the new_method's to each of them just as easily (and > with probably less typing). So, would there ever be a reason to do > something like I wrote above? > > --J E
on 2005-12-11 06:16
jonathan leonard <zjll9@imail.etsu.edu> <zjll9@ima wrote: > (I think it is also known as > metaprogramming). Actually, according to wikipedia, metaprogramming involves only rewrites done at compile time and not run-time (such as lex or yacc, which generate code). So, I guess this would simply be 'self-modifying' code. --J
on 2005-12-11 06:25
ruby-ml wrote: > On 2005.12.11 10:34, "jonathan <zjll9@imail.etsu.edu> > <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu>" > <zjll9@imail.etsu.edu> wrote: >> > can be individually extended. Two instances of MyClass, for example, >> > end >> words, must the singleton always be associated with an instance and not >> >> end } >> non-singleton (i.e., many) instances of the subclasses. > Typically, if I understand you correctly, you could just use this > idiom (unless you want to just eval the whole thing): > > # Classes are constants > # | Inherit MyClass > # | | We can use blocks > # | | | > # V V V > MyClassExtension = Class.new(MyClass) { > def self.some_method() > # ... > end > > def some_method() > # ... > end > } > Oooh. That's cool! In the case I was envisioning, I would want to eval the whole thing (so that classes could be extended dynamically at run-time). --J
on 2005-12-11 16:51
jonathan leonard <zjll9@imail.etsu.edu> <zjll9@ima wrote: > ruby-ml wrote: >> On 2005.12.11 10:34, "jonathan <zjll9@imail.etsu.edu> >> <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu>" >> <zjll9@imail.etsu.edu> wrote: >>> > can be individually extended. Two instances of MyClass, for example, >>> > end >>> words, must the singleton always be associated with an instance and not >>> >>> end } >>> non-singleton (i.e., many) instances of the subclasses. >> Typically, if I understand you correctly, you could just use this >> idiom (unless you want to just eval the whole thing): >> >> # Classes are constants >> # | Inherit MyClass >> # | | We can use blocks >> # | | | >> # V V V >> MyClassExtension = Class.new(MyClass) { >> def self.some_method() >> # ... >> end >> >> def some_method() >> # ... >> end >> } >> > > Oooh. That's cool! In the case I was envisioning, I would want to eval > the whole thing (so that classes could be extended dynamically at > run-time). Just to be clear (I think you have the right idea, but for the benefit of any future ruby miners), you can use the above construct dynamically at runtime. If you are doing a lot of dynamic method naming and such (a proposition of debateable merit as you would have to #send all your messages), it may be easier to use strings in conjunction with one of #(class|module|instance)_eval. > --J E
on 2005-12-11 17:08
On Dec 10, 2005, at 11:16 PM, jonathan leonard wrote: > jonathan leonard <zjll9@imail.etsu.edu> <zjll9@ima wrote: >> (I think it is also known as >> metaprogramming). > > Actually, according to wikipedia, metaprogramming involves only > rewrites > done at compile time and not run-time (such as lex or yacc, which > generate code). So, I guess this would simply be 'self-modifying' > code. That's not how we generally use it in the Ruby community, but keep in mind that Ruby greatly blurs the compile-time, run-time distinction. My buddy calls Unit Tests, Ruby's compile-time error checking. Hard to argue with that. ;) James Edward Gray II
on 2005-12-11 21:09
dblack@wobblini.net wrote: > But the whole thing may indeed > become non-class-based. I'm not sure what that would entail. I kind > of think that if it were something other than a class, one would end > up longing for a "class interface" to it, and then it might as well be > a class.... I tend to agree with you. While on the surface it may seem simpler without the class, I think it actually ends being more complicated. I think the same holds true for aop wraps --another reason to favor of cuts over (or as a foundation for) the proposed hooks. T.
on 2005-12-11 21:21
Hi -- On Sun, 11 Dec 2005, jonathan <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> wrote: > dblack wrote: >> >> The singleton class mechanism is just a way to store those "extra" >> methods. The methods written for a (namely, "x") go in a's singleton >> class; those for b, in b's; etc. These classes are created >> automatically when they are needed. > > Hmm. Ok, so there really is no singleton class for Myclass? In other > words, must the singleton always be associated with an instance and not > a class? Every object (almost) can have a singleton class, including Class objects. > > > extend_class( Myclass ) > x = Myclass_extension.new > x.new_method1 > y = Myclass_extension.new > y.new_method1 > > Some variation of this (where the extended class is named uniquely) > should allow infinitely many extended subclasses and also allow > non-singleton (i.e., many) instances of the subclasses. There are easier ways, such as (I think someone else pointed out) Class.new(superclass). Using eval is a stretch; in fact, I'm fairly confident in saying that it's almost a certain sign that you're doing something which can be done a cleaner way, or that perhaps needs to be rethought entirely. Anyway -- a non-eval version of what you've got above might be something like: class MyClass end def extend_class(classname) ex = Object.const_set(classname.to_s + "_extension", Class.new) ex.class_eval do def new_method1 puts "new method" end end end extend_class(MyClass) x = MyClass_extension.new x.new_method1 > Of course, I suppose you could start with x and y as instances of the > base class and add the new_method's to each of them just as easily (and > with probably less typing). So, would there ever be a reason to do > something like I wrote above? Probably not :-) But it's good to learn all of these permutations, I think. David -- David A. Black dblack@wobblini.net "Ruby for Rails", forthcoming from Manning Publications, April 2006!
on 2005-12-12 05:07
unknown wrote: > > class MyClass > end > > def extend_class(classname) > ex = Object.const_set(classname.to_s + "_extension", Class.new) > ex.class_eval do > def new_method1 > puts "new method" > end > end > end > > extend_class(MyClass) > x = MyClass_extension.new > x.new_method1 > Oh. That's a neat way of doing it. Would the code below also work in order to support a dynamic method name? class MyClass end def extend_class(classname, methodname) ex = Object.const_set(classname.to_s + "_extension", Class.new) ex.class_eval %{ def #(methodname) puts "new method" end } end end --J
on 2005-12-12 05:21
On 2005.12.12 13:07, "jonathan <zjll9@imail.etsu.edu> <zjll9@ima" <zjll9@imail.etsu.edu> wrote: > > puts "new method" > order to support a dynamic method name? > end > end Well, there is always define_method: # This code for illustrative purposes only. This is unadvisable. class Class def extend_by(method_name, &block) o = Object.const_set("#{self.name}Extension", Class.new(self)) o.class_eval { define_method(method_name, &block) } o end end class Foo end Extension = Foo.extend_by('quux') { puts "Hello from quux!" } Extension.new.quux > --J E
on 2005-12-12 07:03
I'm curious why "class method" is being avoided? It certainly seems accurate and matches the use of class methods by languages such as Smalltalk and Objective-C.
on 2005-12-12 07:33
Mark Ericson wrote: > I'm curious why "class method" is being avoided? It certainly seems > accurate and matches the use of class methods by languages such as Smalltalk > and Objective-C. I think "class method" is used in our community, but it is considered a special case -- it's just a singleton method on an object which happens to be a class. A singleton method on an object which isn't a class -- well, that obviously isn't a class method. Hal
on 2005-12-12 08:42
"jonathan <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu>" <zjll9@imail.etsu.edu> wrote: > > Hmm.. Ok. But, with Ruby, you can still dynamically create subclasses > that aren't singletons and extend them as well as instanciate instances > of them, right? That would provide the flexibility I was referring to > above, but I suppose it would require typing quite a few more > characters. So do I understand correctly that Matz designed the whole > singleton creation mechanism ( << ) as a shorthand for doing more > long-winded dynamic creation/enhancing? It's not a subclass, it's an anonymous proxy superclass. It goes into the inheritance chain between the object it extends and the class that object derived from, like so (assume a is a String): [String] --- [class << a] --- [a] Since ruby doesn't have multiple inheritance, you can see why there can (and need!) only be a single proxy superclass. martin
on 2005-12-12 09:10
On Mon, Dec 12, 2005 at 03:30:50PM +0900, Hal Fulton wrote: > Mark Ericson wrote: > >I'm curious why "class method" is being avoided? It certainly seems > >accurate and matches the use of class methods by languages such as > >Smalltalk > >and Objective-C. > > I think "class method" is used in our community, but it is considered > a special case -- it's just a singleton method on an object which happens > to be a class. A singleton method on an object which isn't a class -- > well, that obviously isn't a class method. By the way . . . has anyone considered a name like "singular"? What about "ad lib" instead of "ad hoc"? I've gotta say, though, that I'm partial to the descriptor "eigen". -- Chad Perrin [ CCD CopyWrite | http://ccd.apotheon.org ] unix virus: If you're using a unixlike OS, please forward this to 20 others and erase your system partition.
on 2005-12-12 09:40
On 2005.12.12 17:07, Chad Perrin <perrin@apotheon.com> wrote: > > well, that obviously isn't a class method. > > By the way . . . has anyone considered a name like "singular"? What > about "ad lib" instead of "ad hoc"? > > I've gotta say, though, that I'm partial to the descriptor "eigen". I advocate "pouch" :) In any case, it might be wise to hold some sort of a poll (or perhaps Matz can be coerced to pick the one he prefers) because I have noticed a trend of different groups using different terms for the same thing which in turn has caused some confusion about the feature in general. E
on 2005-12-13 04:59
Eero Saynatkari wrote: > Well, there is always define_method: > > # This code for illustrative purposes only. This is unadvisable. > class Class > def extend_by(method_name, &block) > o = Object.const_set("#{self.name}Extension", Class.new(self)) > o.class_eval { > define_method(method_name, &block) > } > o > end > end > > class Foo > end > > Extension = Foo.extend_by('quux') { puts "Hello from quux!" } > Extension.new.quux Why is the code above unadvisable? --J
on 2005-12-13 05:06
Martin DeMello wrote: > > It's not a subclass, it's an anonymous proxy superclass. It goes into > the inheritance chain between the object it extends and the class that > object derived from, like so (assume a is a String): > > [String] --- [class << a] --- [a] > > Since ruby doesn't have multiple inheritance, you can see why there can > (and need!) only be a single proxy superclass. > So, this means you lose the functionality of a? I thought the whole point was to extend a. The tutorial (http://www.rubygarden.org/ruby?SingletonTutorial) actually doesn't mention whether it is super or sub, i just assumed sub. I suppose whether it was super or sub really doesn't matter except in what you would be referencing by 'self' or 'super' in the added code (i.e., if you are correct, then doing self at class scope level would allow you to access the super class, or doing self at instance scope (in the new code) would reference an instance of the super class. Of course, if you used super in that context, it would reference the original class' grandparent. Are you sure this is how it works? The tutorial doesn't do any of the things I just mentioned, so it can't answer this question. Thanks, --J
on 2005-12-13 05:09
Oops. Nevermind the part about losing functionality. However, I think the discussion of self/super still applies. --J
on 2005-12-13 05:26
jonathan leonard wrote: > Eero Saynatkari wrote: >> Well, there is always define_method: >> >> # This code for illustrative purposes only. This is unadvisable. >> class Class >> def extend_by(method_name, &block) >> o = Object.const_set("#{self.name}Extension", Class.new(self)) >> o.class_eval { >> define_method(method_name, &block) >> } >> o >> end >> end >> >> class Foo >> end >> >> Extension = Foo.extend_by('quux') { puts "Hello from quux!" } >> Extension.new.quux > > Why is the code above unadvisable? I personally think the idiom is a bit suspect but it could just be I have not come across the need for it :) The above merely illustrates that it is quite possible to do that in ruby; however, another way might lead to a better design. (Generally, any types of factories are simple in ruby and the whole duck-typing thing helps, too.) > --J E
on 2005-12-13 05:33
Martin DeMello wrote: > It's not a subclass, it's an anonymous proxy superclass. It goes into > the inheritance chain between the object it extends and the class that > object derived from, like so (assume a is a String): > > [String] --- [class << a] --- [a] > > Since ruby doesn't have multiple inheritance, you can see why there can > (and need!) only be a single proxy superclass. > > martin How about this old chestnut, which I frankly don't understand: http://onestepback.org/images/rubyobjects.png
on 2005-12-13 06:11
Eero Saynatkari wrote: >> Why is the code above unadvisable? > > I personally think the idiom is a bit suspect but it could > just be I have not come across the need for it :) The above > merely illustrates that it is quite possible to do that in > ruby; however, another way might lead to a better design. > > (Generally, any types of factories are simple in ruby and > the whole duck-typing thing helps, too.) > I don't really see how duck-typing is relevant, but I would assume that the idiom used above (i.e., 'const_set', 'class_eval', and 'define_method') could be done in an extension factory (rather than procedurally as above). In other words, you might have a factory called JumpExtensionFactory which could create any object that can jump (e.g., people, animals, monsters, etc.) from a non-jumping object say in a video game model. I suppose it would have to calculate the maximum jump height and length based on other statistics such as leg strength, weight, etc. (which would presumably have to be attributes the object already has or can acquire) and the actual jump height and length based on run-time attributes such as velocity and input force. That is the purpose I can see for this sort of thing. Is that what you mean by utilizing factories? The only real problem I see with this is you really wouldn't want to create a new object, but rather extend the original one. In other words, after a type learns to jump, then all objects of that type should be able to jump (so there's no need to distinguish from a non-jumping version and the jumping version). So, actually, I would call it an JumpExtender or a JumpTeacher (instead of JumpExtensionFactory). (Thinking out loud here). But, hopefully we're closer to the same page now. --J
on 2005-12-13 10:36
On Dec 12, 2005, at 0:07, Chad Perrin wrote: > By the way . . . has anyone considered a name like "singular"? What > about "ad lib" instead of "ad hoc"? > > I've gotta say, though, that I'm partial to the descriptor "eigen". Well, I'm having a terrible time following the distinction between the indefinite number of flavors of this difficult-to-name type of method, but I do know something about naming things. :) Generally, trying to find an existing term, like 'singleton' or 'ad hoc', is a good thing, because lets somebody bring pre-constructed expectations to the process, hopefully saving them time in learning how this particular thing works. Unless, of course, different people have different expectations for that word, or if the thing in question contradicts the expectations in some way. If 'simpleton' and 'singleton' are equally applicable to either of two different cases, as somebody suggested earlier, then these will lead people to *think* they know what will happen, but there's a 50/50 chance that it will be the other. So that's not a good thing. There appears to be some concern that "ad hoc" implies something much broader (?) than this particular usage actually has. That's not a good thing. If you have a situation where none of the existing reasonable terms seem like an adequately non-confusing match, then it's actually much better to use a term that *doesn't* bring a lot of pre-conceived baggage to the table. If you create a term that's *obviously* meaningless or ambiguous, then the first-time user knows right away that they'll have to look it up, instead of erroneously thinking they know what it does just because of the name. Calling them something like "intral methods", "uni methods", "anonic methods," or "eigenz" is better than using a "real" pre-existing word that is a poor fit. "Hmm. Uni methods. Well, I have a hunch what that might be for, but it isn't immediately obvious. I'll just have to read more about it to find out what they actually do."
on 2005-12-13 11:03
Dave Howell wrote: > > On Dec 12, 2005, at 0:07, Chad Perrin wrote: > >> By the way . . . has anyone considered a name like "singular"? What >> about "ad lib" instead of "ad hoc"? >> >> I've gotta say, though, that I'm partial to the descriptor "eigen". > --snip-- > > If you have a situation where none of the existing reasonable terms seem > like an adequately non-confusing match, then it's actually much better > to use a term that *doesn't* bring a lot of pre-conceived baggage to the > table. Well, then there is obviously only one logical choice: Chunky Bacon Class! Regards, Michael
on 2005-12-13 14:10
Hi -- On Tue, 13 Dec 2005, Dave Howell wrote: > do know something about naming things. :) > different cases, as somebody suggested earlier, then these will lead people > erroneously thinking they know what it does just because of the name. Calling > them something like "intral methods", "uni methods", "anonic methods," or > "eigenz" is better than using a "real" pre-existing word that is a poor fit. > "Hmm. Uni methods. Well, I have a hunch what that might be for, but it isn't > immediately obvious. I'll just have to read more about it to find out what > they actually do." A couple of problems with that, in this particular case: First, there's an existing term (singleton method/class) that's under review by Matz, with input from the community. That means that calling them "potato-peel classes", or whatever, not only adds confusion but short-circuits a process that's already underway and that promises to result in a decision and clarification. Second, you can't read more about the thing if you don't know what it's called. All this renaming just adds an extra layer of having to learn about the history of ruby-talk, as well as the features of the Ruby language, in order to know what people are talking about in the first place. The advantages of this elude me. I think the community would be well advised not to assume that the world's interest in keeping track of who uses which home-made synonym for "singleton class" is unlimited. David -- David A. Black dblack@wobblini.net "Ruby for Rails", forthcoming from Manning Publications, April 2006!
on 2005-12-14 03:40
Dave Howell wrote: > Generally, trying to find an existing term, like 'singleton' or 'ad > hoc', is a good thing, because lets somebody bring pre-constructed > expectations to the process, hopefully saving them time in learning how > this particular thing works. I believe, and there is a slight chance that I'm wrong, that the terms simpleton and singleton are synonymous. --J
on 2005-12-14 03:42
Dave Howell wrote: > If 'simpleton' and 'singleton' are equally applicable to either of two > different cases, as somebody suggested earlier, then these will lead > people to *think* they know what will happen, but there's a 50/50 > chance that it will be the other. So that's not a good thing. Well, I think 'simpleton' and 'singleton' are synonymous terms (about 98% sure of that if this were a lifeline). But, the problem would remain if singleton isn't a good fit to begin with. I actually think singleton is a good fit and therefore so is simpleton. --J
on 2005-12-14 04:02
Hi --
On Wed, 14 Dec 2005, jonathan leonard <zjll9@imail.etsu.edu>
<zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> wrote:
>
I think you're laboring under a misunderstanding.
Please see http://dictionary.reference.com/search?q=simpleton
David
--
David A. Black
dblack@wobblini.net
"Ruby for Rails", forthcoming from Manning Publications, April 2006!
on 2005-12-14 04:57
unknown wrote: > I think you're laboring under a misunderstanding. > > Please see http://dictionary.reference.com/search?q=simpleton I don't think so. see: http://foreigndispatches.typepad.com/dispatches/2005/10/the_simpleton_d.html or do a google search for 'simpleton design pattern' for many others. --J
on 2005-12-14 05:07
Hi --
On Wed, 14 Dec 2005, jonathan leonard <zjll9@imail.etsu.edu>
<zjll9@imail.etsu.edu> <zjll9@imail.etsu.edu> wrote:
> or do a google search for 'simpleton design pattern' for many others.
This seems to be some kind of play on words. "Simpleton" is not an
appropriate serious word for a language feature.
David
--
David A. Black
dblack@wobblini.net
"Ruby for Rails", forthcoming from Manning Publications, April 2006!
on 2005-12-14 05:26
unknown wrote: > >> or do a google search for 'simpleton design pattern' for many others. > This seems to be some kind of play on words. "Simpleton" is not an > appropriate serious word for a language feature. > Yea, I agree there is some word playing going on (it may be kinda like releasing a virus into the wild). Some of what the search turned up was making fun of the singleton pattern by calling it simpleton (and the rest could have been accidental misuses). However, I could have sworn that I saw this word used in a more legitimate place (such as a lecture or textbook). If I run across a more authoritative source, I'll share it. Nevertheless, I have to disagree with your 'serious' requirement for words for language features in general and, in particular, concerning simpleton. Take for instance, 'duck typing'. And, I see nothing wrong with simpleton either, if there were an actual language construct which fit the word; although, I admit, it might not fit for 'singleton' as much as I initially thought. However, if you expand your search, you can find people refering to code modules as simpletons, based on the fact that they have a limited, simple set of functionality (check out this page for instance): http://www.roxie.org/knownspace/api_design.html and it does seem to fit their architecture. --J
on 2005-12-14 09:40
On Wed, 14 Dec 2005 03:57:35 -0000, jonathan leonard <zjll9@imail.etsu.edu> wrote: > (David Black) wrote: >> I think you're laboring under a misunderstanding. >> >> Please see http://dictionary.reference.com/search?q=simpleton > > I don't think so. > Lol!
on 2005-12-14 18:21
On Dec 13, 2005, at 10:00 PM, dblack@wobblini.net wrote: > I think you're laboring under a misunderstanding. > > Please see http://dictionary.reference.com/search?q=simpleton > Just for comparision: singleton |Ë?si ng gÉ?ltÉ?n| |Ë?sɪÅ?gÉ?lt(É?)n| |Ë?sɪÅ?g(É?)lt(É?)n| noun a single person or thing of the kind under consideration : splitting the clumps of plants into singletons. â?¢ [often as adj. ] a child or animal born singly, rather than one of a multiple birth : singleton boys. â?¢ (in card games, esp. bridge) a card that is the only one of its suit in a hand. â?¢ Mathematics & Logic a set that contains exactly one element. ORIGIN late 19th cent.: from single , on the pattern of simpleton.
on 2005-12-14 23:02
Logan Capaldo wrote: > Just for comparision: > singleton |Ë?si ng gÉ?ltÉ?n| |Ë?sɪÅ?gÉ?lt(É?)n| |Ë?sɪÅ?g(É?)lt(É?)n| > noun > a single person or thing of the kind under consideration : splitting > the clumps of plants into singletons. > â?¢ [often as adj. ] a child or animal born singly, rather than one of > a multiple birth : singleton boys. > â?¢ (in card games, esp. bridge) a card that is the only one of its > suit in a hand. > â?¢ Mathematics & Logic a set that contains exactly one element. > ORIGIN late 19th cent.: from single , on the pattern of simpleton. What is the source of this definition? This could be my vindication. :) --J
Please log in before posting. Registration is free and takes only a minute.
Existing account
(Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
Log in with Google account | Log in with Yahoo account
No account? Register here.