```On Jan 22, 10:50=A0pm, RichardOnRails
<RichardDummyMailbox58... / USComputerGurus.com> wrote:
> class Z
> =A0 =A0 def self.show_z
> =A0 =A0 =A0 =A0 @@zz ||=3D 0; @@zz +=3D 1
> =A0 =A0 =A0 =A0 puts @@zz
> =A0 =A0 end
> end
> Z.show_z =A0 =A0 =A0 =A0# =3D> 1
> Z.show_z =A0 =A0 =A0 =A0# =3D> 2

The singleton pattern works well for this sort of thing.

require 'singleton' # this is part of Ruby's standard library
class Counter
include Singleton
def count
@count =3D (@count ? @count + 1 : 0)
end
end

a =3D Counter.instance
a.count # =3D> 0
a.count # =3D> 1
b =3D Counter.instance
b.count # =3D> 2

> \$h =3D Hash.new(:y)
> def show_y
> =A0 =A0 \$h[:y] ||=3D 0; \$h[:y] +=3D 1 # =3D> Error msg # Line 18
> =A0 =A0 puts \$h[:y]
> end
> show_y
> show_y

And if you really need something like this (hopefully you don't) try:

\$h =3D Hash.new {|the_hash, a_key| the_hash[a_key] =3D 0}
def show_y
\$h[:y] +=3D 1
puts \$h[:y]
end

and combining them:

require 'singleton'
class Counters
include Singleton
def initialize
@counts =3D Hash.new {|h, k| h[k] =3D 0}
end
def get_count(sym)
@counts[sym] +=3D 1
end
end

c =3D Counter.instance
c.get_count :y # =3D> 1
c.get_count :y # =3D> 2
c.get_count :z # =3D> 1

```