如何添加到 Ruby 中的现有哈希

发布于 2024-11-26 23:50:59 字数 192 浏览 2 评论 0原文

关于添加 key =>;值 对到 Ruby 中现有的填充哈希,我正在学习 Apress 的 Beginning Ruby,并且刚刚完成了哈希章节。

我试图找到最简单的方法来使用哈希实现与数组相同的结果:

x = [1, 2, 3, 4]
x << 5
p x

In regards to adding an key => value pair to an existing populated hash in Ruby, I'm in the process of working through Apress' Beginning Ruby and have just finished the hashes chapter.

I am trying to find the simplest way to achieve the same results with hashes as this does with arrays:

x = [1, 2, 3, 4]
x << 5
p x

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

寻找我们的幸福 2024-12-03 23:50:59

如果您有散列,则可以通过键引用它们来向其中添加项目:

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 通过提供 HashWithIn DifferentAccess 在某种程度上混淆了这一点,它将在 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 上的许多方法一样,! 表明它是一个 就地操作。

If you have a hash, you can add items to it by referencing them by key:

hash = { }
hash[:a] = 'a'
hash[:a]
# => 'a'

Here, like [ ] creates an empty array, { } will create a empty hash.

Arrays have zero or more elements in a specific order, where elements may be duplicated. Hashes have zero or more elements organized by key, where keys may not be duplicated but the values stored in those positions can be.

Hashes in Ruby are very flexible and can have keys of nearly any type you can throw at it. This makes it different from the dictionary structures you find in other languages.

It's important to keep in mind that the specific nature of a key of a hash often matters:

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 confuses this somewhat by providing HashWithIndifferentAccess where it will convert freely between Symbol and String methods of addressing.

You can also index on nearly anything, including classes, numbers, or other Hashes.

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

hash[Object]
# => true

hash[Hash]
# => false

hash[Array]
# => nil

Hashes can be converted to Arrays and vice-versa:

# 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"} 

When it comes to "inserting" things into a Hash you may do it one at a time, or use the merge method to combine hashes:

{ :a => 'a' }.merge(:b => 'b')
# {:a=>'a',:b=>'b'}

Note that this does not alter the original hash, but instead returns a new one. If you want to combine one hash into another, you can use the merge! method:

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'}

Like many methods on String and Array, the ! indicates that it is an in-place operation.

成熟的代价 2024-12-03 23:50:59
my_hash = {:a => 5}
my_hash[:key] = "value"
my_hash = {:a => 5}
my_hash[:key] = "value"
简单爱 2024-12-03 23:50:59

如果您想添加多个:

hash = {:a => 1, :b => 2}
hash.merge! :c => 3, :d => 4
p hash

If you want to add more than one:

hash = {:a => 1, :b => 2}
hash.merge! :c => 3, :d => 4
p hash
完美的未来在梦里 2024-12-03 23:50:59
x = {:ca => "Canada", :us => "United States"}
x[:de] = "Germany"
p x
x = {:ca => "Canada", :us => "United States"}
x[:de] = "Germany"
p x
夜血缘 2024-12-03 23:50:59

您可以使用自 Ruby 2.0 起可用的 double splat 运算符:

h = { a: 1, b: 2 }
h = { **h, c: 3 }
p h
# => {:a=>1, :b=>2, :c=>3}

You can use double splat operator which is available since Ruby 2.0:

h = { a: 1, b: 2 }
h = { **h, c: 3 }
p h
# => {:a=>1, :b=>2, :c=>3}
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 = { a: 'a', b: 'b' }
 => {:a=>"a", :b=>"b"}
hash.merge({ c: 'c', d: 'd' })
 => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 

Returns the merged value.

hash
 => {:a=>"a", :b=>"b"} 

But doesn't modify the caller object

hash = hash.merge({ c: 'c', d: 'd' })
 => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 
hash
 => {:a=>"a", :b=>"b", :c=>"c", :d=>"d"} 

Reassignment does the trick.

孤寂小茶 2024-12-03 23:50:59
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.
hash {}
hash[:a] = 'a'
hash[:b] = 'b'
hash = {:a => 'a' , :b = > b}

You might get your key and value from user input, so you can use Ruby .to_sym can convert a string to a symbol, and .to_i will convert a string to an integer.
For example:

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文