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?
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.
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.
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.
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.
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With