如何在Ruby中添加现有哈希

Tom*_*Tom 94 ruby hash new-operator

关于key => value在Ruby中为现有的填充哈希添加一对,我正在通过Apress的Beginning Ruby工作,刚刚完成了哈希章节.

我试图找到用哈希实现相同结果的最简单方法,就像对数组一样:

x = [1, 2, 3, 4]
x << 5
p x
Run Code Online (Sandbox Code Playgroud)

tad*_*man 182

如果您有哈希,可以通过按键引用项目来添加项目:

hash = { }
hash[:a] = 'a'
hash[:a]
# => 'a'
Run Code Online (Sandbox Code Playgroud)

在这里,就像[ ]创建一个空数组一样,{ }将创建一个空哈希.

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

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' }
Run Code Online (Sandbox Code Playgroud)

Ruby on Rails通过提供HashWithIndifferentAccess来解决这个问题,它可以在Symbol和String寻址方法之间自由转换.

您还可以索引几乎任何东西,包括类,数字或其他哈希.

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

hash[Object]
# => true

hash[Hash]
# => false

hash[Array]
# => nil
Run Code Online (Sandbox Code Playgroud)

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

# 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"} 
Run Code Online (Sandbox Code Playgroud)

当把东西"插入"Hash时你可以一次做一个,或者使用merge方法来组合哈希:

{ :a => 'a' }.merge(:b => 'b')
# {:a=>'a',:b=>'b'}
Run Code Online (Sandbox Code Playgroud)

请注意,这不会改变原始哈希值,而是返回一个新哈希值.如果要将一个哈希合并到另一个哈希,可以使用以下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'}
Run Code Online (Sandbox Code Playgroud)

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

  • 很多有价值的信息,但缺乏最基本的表述,只能由@robbrit回答. (12认同)

rob*_*rit 64

my_hash = {:a => 5}
my_hash[:key] = "value"
Run Code Online (Sandbox Code Playgroud)


Jos*_*ach 34

如果要添加多个:

hash = {:a => 1, :b => 2}
hash.merge! :c => 3, :d => 4
p hash
Run Code Online (Sandbox Code Playgroud)


Jer*_*man 8

x = {:ca => "Canada", :us => "United States"}
x[:de] = "Germany"
p x
Run Code Online (Sandbox Code Playgroud)