关于在Ruby中将key => value对添加到现有的填充哈希中,我正在研究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上的许多方法一样,!表示它是就地操作。

10-05 21:13
查看更多