将一个哈希值保存在另一个哈希值中是常见做法吗?
我想将一些哈希对象保存到集合中(在 Java 世界中将其视为列表)。 我上网搜索Ruby中是否有类似的数据结构,但没有找到。 目前,我一直在尝试将哈希 a[]
保存到哈希 b[]
中,但在尝试从哈希 中获取数据时遇到了问题b[]
。
Ruby 上有内置的集合数据结构吗? 如果不是,将哈希值保存在另一个哈希值中是否是常见做法?
I'd like to save some hash objects to a collection (in the Java world think of it as a List). I search online to see if there is a similar data structure in Ruby and have found none. For the moment being I've been trying to save hash a[]
into hash b[]
, but have been having issues trying to get data out of hash b[]
.
Are there any built-in collection data structures on Ruby? If not, is saving a hash in another hash common practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
到目前为止,这里的所有答案都是关于哈希中的哈希,而不是哈希加哈希,因此出于完整性的原因,我将附注以下内容:
请注意,当您将 B 合并到 A 时,A 拥有的 B 中的任何键都是被覆盖。
All the answers here so far are about Hash in Hash, not Hash plus Hash, so for reasons of completeness, I'll chime in with this:
Note that when you merge B into A, any keys that A had that are in B are overwritten.
Ruby 中的列表是数组。 您可以使用 Hash.to_a。
如果您尝试将哈希 a 与哈希 b 组合,可以使用 Hash .merge
编辑:如果您尝试将哈希 a 插入哈希 b,您可以这样做
Lists in Ruby are arrays. You can use Hash.to_a.
If you are trying to combine hash a with hash b, you can use Hash.merge
EDIT: If you are trying to insert hash a into hash b, you can do
如果是访问哈希中的哈希是问题所在,请尝试:
If it's accessing the hash in the hash that is the problem then try:
这应该没有什么问题。
也许您可以解释一下您遇到的问题。
There shouldn't be any problem with that.
Perhaps you could explain what problems you're encountering.
这个问题并不完全清楚,但我认为你想要一个哈希列表(数组),对吧?
在这种情况下,您可以将它们放入一个数组中,这就像 Java 中的列表:
您可以检索像 list[0] 和 list[1] 这样的哈希值
The question is not completely clear, but I think you want to have a list (array) of hashes, right?
In that case, you can just put them in one array, which is like a list in Java:
You can retrieve those hashes like list[0] and list[1]