From: William James Date: 2006-12-27T07:05:07+09:00 Subject: Re: Hash with two identical keys? Trans wrote: > William James wrote: > > Trans wrote: > > > thanks Ara and Jon, > > > > > > I see what your saying. I was using #== not #eql? in comparing the > > > keys. So I see why it's faling now. How do I get aorund this? I'm > > > caching object based on therr initialization paramaters, which has to > > > be an array. Is there a simpler way or do I have to do something like: > > > > > > class Parameters < Array > > > alias :eql? :== > > > end > > > > > > T. > > > > How about association lists? > > Thanks William! That's what I did and worked (desipite inefficency). > > T. Here's a speed comparison for various numbers of keys: require 'benchmark' $iterations = 40_000 def rand_sym letters = ('a'..'z').to_a sym = "" 8.times{ sym << letters[ rand(letters.size) ] } sym.to_sym end def test_assoc n alist = [] keys = [] while alist.size < n do key = rand_sym unless keys.include?( key ) alist << [ key, true ] keys << key end end $iterations.times{ keys.each{|key| fail if alist.assoc(key)[1] != true } } end def test_hash n hash = {} keys = [] while hash.size < n key = rand_sym unless hash.include?( key ) hash[key] = true keys << key end end $iterations.times{ keys.each{|key| fail if hash[key] != true } } end Benchmark.bm(8) do |x| [1,2,3,7,20].each{ |n| x.report("assoc %2d" % n) { test_assoc n } x.report("hash %2d" % n) { test_hash n } } end user system total real assoc 1 0.150000 0.000000 0.150000 ( 0.171000) hash 1 0.130000 0.000000 0.130000 ( 0.140000) assoc 2 0.291000 0.000000 0.291000 ( 0.310000) hash 2 0.200000 0.000000 0.200000 ( 0.231000) assoc 3 0.440000 0.000000 0.440000 ( 0.460000) hash 3 0.291000 0.000000 0.291000 ( 0.311000) assoc 7 1.172000 0.000000 1.172000 ( 1.252000) hash 7 0.590000 0.000000 0.590000 ( 0.640000) assoc 20 5.188000 0.000000 5.188000 ( 5.578000) hash 20 1.652000 0.000000 1.652000 ( 1.813000)