This works, but there must be a more natural way to do
this. Can someone point the way?

Thanks,
-
nord

#!/bin/ruby

class HashAutoVivify < Hash

  # create sub-hashes automatically
  def [](n)
     self[n]=HashAutoZero.new if super(n)==nil
     super(n)
  end

  # "values" in sub-hash automatically have initial
value 0
  class HashAutoZero < Hash
    def [](n)
       self[n]=0 if super(n)==nil
       super(n)
    end
  end

  def printSortedBy(sortSpecifier='keys')
    puts "---- sorted by #{sortSpecifier}"
    self.keys.sort.each do | m |
      puts m
      if sortSpecifier == 'keys'
        self[m].keys.sort_by {|a| a }.each do | k |
          puts "  #{k.ljust(12)}  #{self[m][k]}"
        end
      elsif sortSpecifier == 'vals'
        self[m].keys.sort_by {|a| -self[m][a] }.each
do | k |
          puts "  #{k.ljust(12)}  #{self[m][k]}"
        end
      end
    end
  end

  def printByKeys
    printSortedBy('keys')
  end

  def printByVals
    printSortedBy('vals')
  end
end


metaData = HashAutoVivify.new
metaData['fruit']['apple'] = 13
metaData['fruit']['mango'] = 7
metaData['fruit']['banana'] = 11
metaData['fruit']['cherry'] = 17
metaData['veg']['eggplant'] = 7
metaData['veg']['artichoke'] += 19
metaData['veg']['green bean'] -= 5
metaData['veg']['squash'] += 2
metaData.printByKeys
metaData.printByVals


__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com