如何添加到 Ruby 中的现有哈希
关于添加 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您有散列,则可以通过键引用它们来向其中添加项目:
这里,就像
[ ]
创建一个空数组一样,{ }
将创建一个空散列。数组具有特定顺序的零个或多个元素,其中元素可能重复。哈希有零个或多个按键组织的元素,其中键可能不会重复,但存储在这些位置的值可以重复。
Ruby 中的哈希非常灵活,几乎可以拥有任何类型的键。这使得它与其他语言中的字典结构不同。
重要的是要记住,散列键的特定性质通常很重要:
Ruby on Rails 通过提供 HashWithIn DifferentAccess 在某种程度上混淆了这一点,它将在 Symbol 和 String 寻址方法之间自由转换。
您还可以对几乎所有内容建立索引,包括类、数字或其他哈希。
哈希可以转换为数组,反之亦然:
当涉及到将事物“插入”到哈希中时,您可以一次插入一个,或者使用
merge
方法来组合哈希:请注意,不会改变原始哈希值,而是返回一个新的哈希值。如果要将一个散列合并到另一个散列中,可以使用
merge!
方法:与 String 和 Array 上的许多方法一样,
!
表明它是一个 就地操作。If you have a hash, you can add items to it by referencing them by key:
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:
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.
Hashes can be converted to Arrays and vice-versa:
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: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:Like many methods on String and Array, the
!
indicates that it is an in-place operation.如果您想添加多个:
If you want to add more than one:
您可以使用自 Ruby 2.0 起可用的 double splat 运算符:
You can use double splat operator which is available since Ruby 2.0:
返回合并后的值。
但不会修改调用者对象
重新分配可以解决问题。
Returns the merged value.
But doesn't modify the caller object
Reassignment does the trick.
您可能会从用户输入中获取键和值,因此您可以使用 Ruby .to_sym 可以将字符串转换为符号,而 .to_i 将字符串转换为整数。
例如:
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: