ruby hash-table使用现有密钥插入新元素

时间:2013-04-21 12:53:27

标签: ruby hashtable

假设我有一个单词数组,不同的单词可能有不同的长度,我想按长度组织它们。所以稍后我可以通过给出一个长度参数来访问所有共享相同长度的单词。

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

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

2 个答案:

答案 0 :(得分: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"
    ]
}

答案 1 :(得分: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"]}