ruby - 如何添加到 Ruby 中的现有哈希

标签 ruby new-operator hash

关于将 key => value 对添加到 Ruby 中现有的已填充哈希,我正在研究 Apress 的 Beginning Ruby,并且刚刚完成哈希章节。

我正在尝试找到最简单的方法来使用散列实现与数组相同的结果:

x = [1, 2, 3, 4]
x << 5
p x

最佳答案

如果你有一个散列,你可以通过按键引用它们来添加项目:

hash = { }
hash[:a] = 'a'
hash[:a]
# => 'a'

在这里,就像 [ ] 创建一个空数组一样,{ } 将创建一个空散列。

数组有零个或多个按特定顺序排列的元素,其中元素可以重复。哈希具有零个或多个元素按键组织,其中键可能不会重复,但存储在这些位置的值可以。

Ruby 中的哈希非常灵活,几乎可以包含任何类型的键。这使得它不同于您在其他语言中找到的字典结构。

重要的是要记住,哈希键的特定性质通常很重要:

hash = { :a => 'a' }

# Fetch with Symbol :a finds the right value
hash[:a]
# => 'a'

# Fetch with the String 'a' finds nothing
hash['a']
# => nil

# Assignment with the key :b adds a new entry
hash[:b] = 'Bee'

# This is then available immediately
hash[:b]
# => "Bee"

# The hash now contains both keys
hash
# => { :a => 'a', :b => 'Bee' }

Ruby on Rails 通过提供 HashWithIndifferentAccess 在某种程度上混淆了这一点,它可以在 Symbol 和 String 寻址方法之间自由转换。

您还可以索引几乎所有内容,包括类、数字或其他哈希值。

hash = { Object => true, Hash => false }

hash[Object]
# => true

hash[Hash]
# => false

hash[Array]
# => nil

哈希可以转换为数组,反之亦然:

# Like many things, Hash supports .to_a
{ :a => 'a' }.to_a
# => [[:a, "a"]]

# Hash also has a handy Hash[] method to create new hashes from arrays
Hash[[[:a, "a"]]]
# => {:a=>"a"} 

当谈到将东西“插入”到哈希中时,您可以一次插入一个,或者使用 merge 方法组合哈希:

{ :a => 'a' }.merge(:b => 'b')
# {:a=>'a',:b=>'b'}

请注意,这不会改变原始哈希值,而是返回一个新哈希值。如果你想将一个散列组合到另一个散列中,你可以使用 merge! 方法:

hash = { :a => 'a' }

# Returns the result of hash combined with a new hash, but does not alter
# the original hash.
hash.merge(:b => 'b')
# => {:a=>'a',:b=>'b'}

# Nothing has been altered in the original
hash
# => {:a=>'a'}

# Combine the two hashes and store the result in the original
hash.merge!(:b => 'b')
# => {:a=>'a',:b=>'b'}

# Hash has now been altered
hash
# => {:a=>'a',:b=>'b'}

与 String 和 Array 上的许多方法一样,! 表示这是一个就地操作。

关于ruby - 如何添加到 Ruby 中的现有哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6863771/

相关文章:

c++ - 为什么在这个链表的实现中,这个 C++ 构造函数在同一个内存位置被调用了两次?

MySQL PASSWORD() 函数和 SpringSecurity ShaPasswordEncoder

c++ - 统计大数据流中每个元素出现的次数

ruby - 在 Watir 脚本中调用 Watir 脚本

ruby-on-rails - 如何删除 routes.rb 中为路径中的参数生成的前缀

ruby - 在 REPL 中调试本地 gem

ruby - 如何在 Padrino 应用程序中安装 Sinatra 应用程序?

c++ - 是否可以将新分配的 block 初始化为 0?

c++ - 下面的内存分配有用吗?

python - 如何应用哈希算法而不是 for 循环来降低 python 中的时间复杂度?