2

我想创建一个查找表来查找数组中对象的索引:

获取一个数组["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]}]

我觉得有更优雅的解决方案可以做到这一点,欢迎任何想法!

4

4 回答 4

4

这个怎么样:

Hash[array.zip 0..array.length]
于 2012-10-17T21:54:55.283 回答
2
lookup  = Hash[array.each_with_index.map{|el,i| [el, i]}]

@Mark Thomas 的回答比我的还要快:

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)
于 2012-10-17T21:52:51.867 回答
2

比 apneadiving 的代码稍慢,但更简单:

 Hash[array.map.with_index.to_a]
于 2012-10-18T03:45:40.677 回答
1

也许这个?

lookup = {}
arr.each_with_index { |elem,index|  lookup[elem] = index }
于 2012-10-17T21:41:48.670 回答