From: Robert Klemme Date: 2003-03-19T02:12:05+09:00 Subject: Re: Hash load and GC This is a multi-part message in MIME format. ------=_NextPart_000_0011_01C2ED78.94794870 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hi, I hacked something together using automated marshalling. Your solution could then be realized like this: def getWords() InstanceCache.load "words.txt" do |f| h={} f.each { |line| h[line]=1 } h end end hash = getWords() Regards robert ------=_NextPart_000_0011_01C2ED78.94794870 Content-Type: application/octet-stream; name="InstanceCache.rb" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="InstanceCache.rb" =3Dbegin =3D Synopsis This example reads a file into a hash. Lines must follow the pattern "key=3Dvalue". For this example the difference between parsing = manually and loading via Marshal#load() is approx. 30. require 'InstanceCache' def get() InstanceCache.load "map.txt" do |f| h=3D{} f.each do |line| n, key, value =3D = *(/^\s*([^\s=3D]+)\s*=3D\s*(.*)$/.match(line).to_a) h[key]=3Dvalue if key && value end h end end =3D Description This module provides for automated loading of instances from a = marshalled version if that is newer than a file from which they are otherwise = parsed. =3D Module Methods --- InstanceCache::load( fileName, cacheFileName=3Dnil ) { parser block = } This method loads either from the marshalled version or from the = file denoted by fileName. If cacheFileName is omitted it will be build = by appending ".cache" to fileName. =3D Private Methods --- InstanceCache::newer?( fileA, fileB ) Returns true if fileA is newer than fileB or if fileB does not = exist. =3Dend module InstanceCache def InstanceCache.load(fileName, cacheFileName=3Dnil, &parser) cacheFileName =3D fileName + ".cache" unless cacheFileName if newer?(fileName, cacheFileName) # need to recache puts "recache" hash =3D File.open(fileName, &parser) File.open(cacheFileName, "w") {|f| Marshal.dump(hash, f)} hash else # load directly puts "load" File.open(cacheFileName, "r") {|f| Marshal.load(f)} end end private def InstanceCache.newer?(fileA, fileB) begin File.stat(fileA).mtime > File.stat(fileB).mtime rescue Errno::ENOENT =3D> e e.message =3D~ Regexp.new("\"#{fileB}\"$") end end end ------=_NextPart_000_0011_01C2ED78.94794870--