From: RichardOnRails Date: 2011-01-24T04:20:53+09:00 Subject: Re: Easiest way in Ruby to express "given this, set target to this if nil or undefined, else increment by this" On Jan 23, 11:10 am, yermej wrote: > On Jan 22, 10:50 pm, RichardOnRails > > 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 Thanks for introducing me to the Singleton class from the Ruby library. I'm going to test whether that'll be work best for my current project. Best wishes, Richard