我想创建一个查找表来查找数组中对象的索引:
获取数组["a", "b", "c"]
并为每个对象的索引生成查找哈希表{"a"=>0, "b"=>1, "c"=>2}
我能想到的最简单的方法是:
i = 0
lookup = array.each_with_object({}) do |value,hash|
hash[value] = i
i += 1
end
和
i = -1
lookup = Hash[array.map {|x| [x, i+=1]}]
我觉得这样做有更优雅的解决方案,欢迎任何想法!
答案 0 :(得分:4)
这个怎么样:
Hash[array.zip 0..array.length]
答案 1 :(得分:2)
lookup = Hash[array.each_with_index.map{|el,i| [el, i]}]
array = (0..100000).to_a;
Benchmark.bm do |x|
x.report { Hash[array.each_with_index.map{|el,i| [el, i]}] }
x.report { Hash[array.zip 0..array.length] }
end
user system total real
0.050000 0.010000 0.060000 ( 0.053233)
0.040000 0.000000 0.040000 ( 0.036471)
答案 2 :(得分:2)
比apneadiving的代码略慢,但更简单:
Hash[array.map.with_index.to_a]
答案 3 :(得分:1)
也许这个?
lookup = {}
arr.each_with_index { |elem,index| lookup[elem] = index }