From: "David A. Black" Date: 2004-10-21T11:34:26+09:00 Subject: Re: Singleton Class or Module Functions? Hi -- On Thu, 21 Oct 2004, trans. (T. Onoma) wrote: > On Wednesday 20 October 2004 08:44 pm, David A. Black wrote: > | Hi -- > | > | On Thu, 21 Oct 2004, trans. (T. Onoma) wrote: > | > I've come across this seemingly indistinct option too many times now. > | > Which is better? Why choose one over the other? > | > > | > module ThisInstance > | > class << self > | > def hello > | > puts "Hello World!" > | > end > | > end > | > end > | > > | > ThisInstance.ameth > | > > | > or > | > > | > class This > | > include Singleton > | > def hello > | > puts "Hello World!" > | > end > | > end > | > > | > This.instance.ameth > | > | (Do you mean 'hello' rather than 'ameth'?) > > Yes. > > | I'm not sure what you mean. What's the connection between them? > > It seems the above two types of constructs can be used interchangeably. They > both have but one "instance". The both have the same access to methods. The > singleton has to be instantiated the first go around, but since that's behind > the scenes, that doesn't really make any difference (or does it?). It depends what you mean by "difference" :-) It's true that in both cases you have an object with sole access to a method. But that's true for any singleton method -- for example: a = Object.new def a.hello; puts "Hello World!"; end In any such case, I suppose you could do: class A; include Singleton; def hello.... end; end a = A.instance But that seems like the long way around. I guess another difference is that adding a method on a singleton basis to an object (as in your first example and my first example) means that you can control difference in a granular way; that is, you could have two objects of the same class, whose types were different *only* with respect to one method: a = Something.new b = Something.new def a.hello; ...; end A Singleton-including class does not allow for this kind of relation between two objects. David -- David A. Black dblack@wobblini.net