关于将 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/