Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 706
Sushanth CS Avatar asked Nov 24 '10 12:11

Sushanth CS


People also ask

What are associative arrays in programming?

In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection.

What is array explain associative array with example?

An array refers to a data structure storing one or more related types of values in a single value. For instance, if you are looking to store 100 numbers, instead of specifying 100 variables, you can simply define an array of length 100.N.

What is hash method Ruby?

In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.

How do you create an array in Ruby?

Using new class method A Ruby array is constructed by calling ::new method with zero, one or more than one arguments. Syntax: arrayName = Array. new.


2 Answers

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/

like image 169
noodl Avatar answered Sep 24 '22 02:09

noodl


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'} 
like image 43
newUserNameHere Avatar answered Sep 24 '22 02:09

newUserNameHere