Trans said:
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)