From: Robert Klemme Date: 2003-10-02T18:05:33+09:00 Subject: Re: Array and hash iteration questions "Ben Giddings" schrieb im Newsbeitrag news:3F7B0BAC.7030305@infofiend.com... > Robert Klemme wrote: > > cases = Hash.new {|h,k| h[k] = [0, 0]} > > Ah. I couldn't remember how to use the block form properly. I'm actually > going to use: > > cases = Hash.new {|hash, key| hash[key] = Hash.new(0)} > > Because it will make some of the later stuff more clear like > > cases[case]['Number'] += 1 > cases[case]['Errors'] += 1 if arr[OFFSET] =~ /Error/ No need to use a Hash for this... Number = 0 Errors = 1 cases[case][Number] += 1 cases[case][Errors] += 1 if arr[OFFSET] =~ /Error/ I might be a bit pricky, but storing the array ref saves one hash lookup. It *can* affect performance if you have a large amount of cases... (see below; although the timing is dominated by the iteration here, you can see that the array is faster) counters = cases[case] counters[Number] += 1 counters[Errors] += 1 if arr[OFFSET] =~ /Error/ You could as well do cases[case].instance_eval do self[Number] += 1 self[Errors] += 1 if arr[OFFSET] =~ /Error/ end I'm getting carried away... :-) > > cases.sort.each do |ca, counter| > > printf "%10s: %4d", ca, counter[0] > > printf " %4d", counter[1] if counter[1] > 0 > > print "\n" > > end > > Aha, I just assumed hash didn't have a sort method, because the concept of > a "sorted hash" seemed meaningless, but since it actually returns an array > containing [key, value] pairs, that's perfect! It is! Thanks to Matz's wisdom. > Thanks Robert You're welcome. Kind regards robert 10:17:02 [ruby]: ruby -rprofile lookups.rb % cumulative self self total time seconds seconds calls ms/call ms/call name 62.50 13.93 13.93 2 6962.50 11140.50 Integer#upto 26.22 19.77 5.84 100001 0.06 0.06 Hash#[] 11.28 22.28 2.51 100001 0.03 0.03 Array#[] 0.07 22.30 0.01 1 15.00 15.00 Profiler__.start_profile 0.00 22.30 0.00 2 0.00 11140.50 Object#test 0.00 22.30 0.00 3 0.00 0.00 Module#method_added 0.00 22.30 0.00 1 0.00 11171.00 Object#testArray 0.00 22.30 0.00 1 0.00 22281.00 #toplevel 0.00 22.30 0.00 1 0.00 11110.00 Object#testHash 10:17:25 [ruby]: cat lookups.rb def test(coll) 0.upto( 100000 ) do coll[2] end end def testHash test( { 0 => 0, 1 => 1, 2 => 2 } ) end def testArray test( [0, 1, 2] ) end testHash testArray 10:18:15 [ruby]: