关于将key => value对添加到Ruby中现有的填充散列中,我正在研究Apress的入门Ruby,刚刚完成了散列一章。
我正在尝试寻找一种最简单的方法来获得与数组相同的散列结果:
x = [1, 2, 3, 4]
x << 5
p x发布于 2011-07-29 03:09:31
如果你有一个哈希表,你可以通过键引用来添加项目:
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,它可以在符号和字符串寻址方法之间自由转换,这有点让人困惑。
您还可以对几乎任何内容进行索引,包括类、数字或其他散列。
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"} { :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'}像字符串和数组上的许多方法一样,!表明它是一个就地操作。
发布于 2011-07-29 02:24:47
my_hash = {:a => 5}
my_hash[:key] = "value"发布于 2011-07-29 02:28:45
如果要添加多个:
hash = {:a => 1, :b => 2}
hash.merge! :c => 3, :d => 4
p hashhttps://stackoverflow.com/questions/6863771
复制相似问题