2013-04-21 18 views
1

假設我有一組單詞,不同的單詞可能有不同的長度,我想按其長度組織它們。因此,稍後我可以通過給出長度參數來訪問所有具有相同長度的單詞。紅寶石哈希表插入帶有現有密鑰的新元素

words = Array.new() 
#fill words by reading file 

words.each do |word| 
    #add word to hash table, key is the length of this word 
    #what can I do? 
end 

我檢查堆棧溢出等問題和答案,但沒有人告訴如何舊密鑰而下插入一個新的值保存所有的人都在一個陣列的形式。

回答

6

從文件中讀取後話,你可以使用group_by來創建一個散列:

data = %w[one two three four five six seven eight nine ten] 
hash = data.group_by{ |w| w.size } 

在這一點上,hash是:

 
{ 
    3 => [ 
     [0] "one", 
     [1] "two", 
     [2] "six", 
     [3] "ten" 
    ], 
    5 => [ 
     [0] "three", 
     [1] "seven", 
     [2] "eight" 
    ], 
    4 => [ 
     [0] "four", 
     [1] "five", 
     [2] "nine" 
    ] 
} 
+0

太棒了!謝謝 – hihell 2013-04-21 13:09:10

+2

或者像往常一樣,'group_by(&:size)'。 – sawa 2013-04-21 13:38:21

+0

我仍然在使用示例代碼中的proc-symbols。就在我認爲這是安全的時候,有人彈出運行1.8並且不承認它。 : -/ – 2013-04-21 13:50:15

0
%w(he is a good man).inject({}){|temp,ob| temp[ob.length] ||= [];temp[ob.length] = (temp[ob.length] + [ob]);temp} 

輸出:

{2=>["he", "is"], 1=>["a"], 4=>["good"], 3=>["man"]} 

require 'pp' 
pp %w[one two three four five six seven eight nine ten].inject({}){|temp,ob| temp[ob.length] ||= [];temp[ob.length] = (temp[ob.length] + [ob]);temp} 

輸出:

{3=>["one", "two", "six", "ten"], 
5=>["three", "seven", "eight"], 
4=>["four", "five", "nine"]} 
+0

感謝,但是這一點我很難理解,我需要學習更多的Ruby語法。 – hihell 2013-04-23 04:23:05