2012-10-17 100 views
2

我想創建一個查找表以找到對象的索引中的數組:生成哈希查找表的對象的索引陣列

EET陣列["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

如何:

Hash[array.zip 0..array.length] 
+0

真的很好! +1 – apneadiving

+0

只是做了基準(代碼在我的答案),你的想法更快 – apneadiving

1

也許這樣?

lookup = {} 
arr.each_with_index { |elem,index| lookup[elem] = index } 
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) 
+0

感謝您的答案和基準! 雖然你的答案很有趣,但我從來沒有見過像這樣鏈接過的each_with_index和map。你能詳細說明它是如何工作的嗎? – rickypai

+0

在我的機器上,使用完全相同的基準測試代碼,您的代碼比Mark Thomas的運行速度更快。 – sawa

+0

@randomtaiwanese:'each_with_index'爲您提供一個枚舉器,poiting給數組的每個元素+它是索引。當你使用'map'時,你只需檢索枚舉值並構建你的數組。更清晰? – apneadiving

2

比apneadiving的代碼稍微慢一些,但更簡單:

Hash[array.map.with_index.to_a] 
+0

是看起來更好:) +1 – apneadiving