ruby 哈希表使用现有键插入新元素

标签 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

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

最佳答案

从文件中读取单词后,您可以使用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/

相关文章:

ruby - Ruby 中 Array#map 的隐式返回值

ruby-on-rails - 在 rails 3 中形成带有 mustache 的助手

ruby-on-rails - 如何在不删除所有较新迁移的情况下再次运行迁移?

c# - 无法将类型为 'System.String' 的对象转换为类型 'System.Collections.Hashtable'

Powershell 克隆有序哈希表

c++ - 在 Makefile 中链接时定义变量的问题

java - 如何将 HashTable 值作为 Arraylist?

c# - 从哈希表中读取匹配的记录到类对象中

ruby-on-rails - Rails ransack gem 以键值对作为参数搜索 jsonb 列

ruby-on-rails - Rails for Zombies Lab 4 > 练习 3