Ruby 中的关联数组
Ruby 有关联数组吗?
例如:
a = Array.new
a["Peter"] = 32
a["Quagmire"] = 'asdas'
在 Ruby 中创建此类数据结构的最简单方法是什么?
Does Ruby have associative arrays?
For eg:
a = Array.new
a["Peter"] = 32
a["Quagmire"] = 'asdas'
What is the easiest method to create such an data structure in Ruby?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与将数组和哈希合并在一起的 PHP 不同,在 Ruby(以及几乎所有其他语言)中,它们是独立的东西。
http://ruby-doc.org/core/classes/Hash.html
在你的情况下,它是:
有几本免费的关于 ruby 和在线模拟器等的介绍性书籍。
http:// www.ruby-doc.org/
Unlike PHP which conflates arrays and hashes, in Ruby (and practically every other language) they're a separate thing.
http://ruby-doc.org/core/classes/Hash.html
In your case it'd be:
There are several freely available introductory books on ruby and online simulators etc.
http://www.ruby-doc.org/
使用哈希,这里有一些关于如何开始的示例(所有这些都做同样的事情,只是语法不同):
或者你可以这样做:
或者甚至是单行:
Use hashes, here's some examples on how to get started (all of these do the same thing, just different syntax):
Or you could do:
Or even a one liner:
为了完整起见,值得注意的是 Ruby 确实提供了
Array#assoc
和Array#rassoc
方法为数组数组添加“类似散列的查找”:请记住,与 Ruby 散列不同,其中查找时间是常量
O(1)
,assoc
和rassoc
都具有线性时间O(n)
。您可以通过查看 Ruby 源代码来了解原因每个方法的 Github。因此,尽管理论上您可以在 Ruby 中使用数组组成的数组来实现“类似散列”,但您可能只想使用
assoc/rassoc
方法,如果你给定一个数组数组 - 也许通过一些你无法控制的外部 API - 否则在几乎所有其他情况下,使用哈希将是更好的路线。For completeness, it's interesting to note that Ruby does provide
Array#assoc
andArray#rassoc
methods that add "hash like lookup" for an array of arrays:Keep in mind that unlike a Ruby hash where lookup time is a constant
O(1)
, bothassoc
andrassoc
have a linear timeO(n)
. You can see why this is by having a look at the Ruby source code on Github for each method.So, although in theory you can use an array of arrays to be "hash like" in Ruby, it's likely you'll only ever want to use the
assoc/rassoc
methods if you are given an array of arrays - maybe via some external API you have no control over - and otherwise in almost all other circumstances, using a Hash will be the better route.