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

我检查了堆栈溢出中的其他问题和答案,但没有一个告诉如何在旧键下插入一个新值,同时将它们全部保持在数组形式中。

4

2 回答 2

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] "一",
        [1] “二”,
        [2]“六”,
        [3]“十”
    ],
    5 => [
        [0]“三”,
        [1] “七”,
        [2]“八”
    ],
    4 => [
        [0]“四”,
        [1]“五”,
        [2]“九”
    ]
}
于 2013-04-21T12:58:30.837 回答
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"]}
于 2013-04-21T12:56:33.043 回答