假设我有一个单词数组,不同的单词可能有不同的长度,我想按长度组织它们。所以稍后我可以通过给定一个长度参数来访问所有共享相同长度的单词。
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
我检查了堆栈溢出中的其他问题和答案,但没有一个告诉我们如何在旧键下插入一个新值,同时将它们全部保持为数组形式。
最佳答案
从文件中读取单词后,您可以使用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" ] }
关于ruby 哈希表使用现有键插入新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16131313/