Ruby : Associative Arrays

2019-01-22 11:18发布

问题:

Does Ruby on rails have associative arrays?

For eg:

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

What is the easiest method to create such an array structure in Ruby?

回答1:

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/



回答2:

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'}