On Jan 22, 10:50  
<RichardDummyMailbox58... / USComputerGurus.com> wrote:
> class Z
> def self.show_z
> @@zz ||= 0; @@zz += 1
> puts @@zz
> end
> end
> Z.show_z  => 1
> Z.show_z  => 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 = (@count ? @count + 1 : 0)
  end
end

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

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

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

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

and combining them:

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

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