开发者

Associative Arrays in 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开发者_如何学Python?


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:

a = {'Peter' => 32, 'Quagmire' => 'asdas'}

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):

a = Hash.new
a["Peter"] = 32
a["Quagmire"] = 'asdas'

Or you could do:

a = {}
a["Peter"] = 32
a["Quagmire"] = 'asdas'

Or even a one liner:

a = {"Peter" => 32, "Quagmire" => 'gigity'}


For completeness, it's interesting to note that Ruby does provide Array#assoc and Array#rassoc methods that add "hash like lookup" for an array of arrays:

arr = [
  ['London', 'England'],
  ['Moscow', 'Russia'],
  ['Seattle', 'USA']
]

arr.assoc('Seattle') #=> '['Seattle', 'USA']
arr.rassoc('Russia') #=> ['Moscow', 'Russia']

Keep in mind that unlike a Ruby hash where lookup time is a constant O(1), both assoc and rassoc have a linear time O(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜