Answers:
如果您有哈希,则可以通过键引用将它们添加到哈希中:
hash = { }
hash[:a] = 'a'
hash[:a]
# => 'a'
在这里,就像[ ]
创建一个空数组一样,{ }
将创建一个空哈希。
数组按特定顺序具有零个或多个元素,其中元素可以重复。哈希具有由key组成的零个或多个元素,其中的密钥可能不会重复,但存储在这些位置的值可以重复。
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使其在符号和字符串寻址方法之间自由转换而有些困惑。
您还可以索引几乎所有内容,包括类,数字或其他哈希。
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上的许多方法一样,!
表示这是就地操作。
如果要添加多个:
hash = {:a => 1, :b => 2}
hash.merge! :c => 3, :d => 4
p hash
hash = { a: 'a', b: 'b' }
=> {:a=>"a", :b=>"b"}
hash.merge({ c: 'c', d: 'd' })
=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}
返回合并值。
hash
=> {:a=>"a", :b=>"b"}
但不修改调用者对象
hash = hash.merge({ c: 'c', d: 'd' })
=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}
hash
=> {:a=>"a", :b=>"b", :c=>"c", :d=>"d"}
重新分配可以解决问题。
hash {}
hash[:a] = 'a'
hash[:b] = 'b'
hash = {:a => 'a' , :b = > b}
您可能会从用户输入中获取键和值,因此可以使用Ruby .to_sym 可以将字符串转换为符号,而.to_i可以将字符串转换为整数。
例如:
movies ={}
movie = gets.chomp
rating = gets.chomp
movies[movie.to_sym] = rating.to_int
# movie will convert to a symbol as a key in our hash, and
# rating will be an integer as a value.
您可以使用从Ruby 2.0开始可用的double splat运算符:
h = { a: 1, b: 2 }
h = { **h, c: 3 }
p h
# => {:a=>1, :b=>2, :c=>3}