46

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?

Rodrigue
  • 3,617
  • 2
  • 37
  • 49
Sushanth CS
  • 2,412
  • 3
  • 23
  • 23

3 Answers3

77

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/

noodl
  • 17,143
  • 3
  • 57
  • 55
  • 24
    In other words: you have to just replace "`a = Array.new`" with "`a = Hash.new`". – Arsen7 Nov 24 '10 at 13:21
  • worth noting that ruby seems to have confused hashes with data structures that use hashes for lookups - e.g. hash table/hash map. in most other contexts these concepts are not confused – jheriko Oct 15 '16 at 14:24
  • 2
    RE: "...[associative] arrays and hashes... in Ruby (and practically every other language) they're a separate thing." Wikipedia lists a dozen others "like PHP" in this regard (see: "Associative Array") -- not arguing, but it feels like this comment distracts from the answer. – HoldOffHunger Jun 27 '18 at 22:51
33

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'}
Zombies
  • 25,039
  • 43
  • 140
  • 225
newUserNameHere
  • 17,348
  • 18
  • 49
  • 79
3

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.

calebkm
  • 1,013
  • 4
  • 17