Hi --

On Sat, 10 Dec 2005, jonathan <zjll9 / imail.etsu.edu> <zjll9 / imail.etsu.edu> wrote:

> dblack wrote:
>> Anyway -- I'm trying to follow along but not sure what you mean by
>> classes that have nothing but class methods and class data.  Can you
>> give a code example of such a class?
>>
>
> Here's a very simple example (a global counter):
>
> <code>
>
> class SingletonCounter
>  private_class_method :new
>  attr_accessor :count
>  @@counter = nil  # class var which pts to instance
>  def initialize( count )
>    @count = count
>  end
>  def SingletonCounter.create
>    @@counter = new( 0 ) unless @@counter
>    @@counter
>  end
>  def increment( inc_amt )
>    @count += inc_amt
>    return @count
>  end
> end
>
> class Counter
>  @@count = 0                      # class variable
>  def Counter.increment( inc_amt ) # class method
>    @@count = @@count + inc_amt
>    return @@count
>  end
> end
>
> sc = SingletonCounter.create
> print sc.increment( 9 )
> print sc.increment( 4 )
>
> sc2 = SingletonCounter.create
> print sc2.increment( 3 ) # points to same underlying obj as sc
>
> c = Counter.new
> print Counter.increment( 9 )  # in C#, you could do c.increment( 9 )
> here
> print Counter.increment( 4 )
>
> c2 = Counter.new
> print Counter.increment( 3 )
>
> </code>
>
> The first class is a true singleton and the second class is what is *in
> essence* a singleton, but known as a static class in C#.

In Ruby it's just known as a class :-)  I'd highly recommend not
trying to shoehorn the term "static" into Ruby.  It's never going to
be a good fit.

(Don't neglect the Singleton module, by the way, which will do the
singleton-ing for you.)

There's nothing at the language level that stops you from adding an
instance method to Counter.  You can give a name to a style of coding
where you don't write instance methods, but it's definitely not a
language feature.


David

-- 
David A. Black
dblack / wobblini.net

"Ruby for Rails", forthcoming from Manning Publications, April 2006!