Ruby Arrays and Hashes

While at General Assembly, one of the first concepts we learned was how to work with arrays and hashes in Ruby. Both are common data types used to store and retrieve information and will probably be used in just about any project you work on. This is just a quick and dirty look at both.

An example of an array would be:

    colors = ["red", "blue", "green"]

If I wanted to return all the colors, I would simply call “colors”:

    colors
    #=>[
        [0] "red",
        [1] "blue",
        [2] "green"
    ]

If I only want to return one of the colors, I can call it by its index number, like so:

colors[0]
#=>"red"

colors[1]
#=>"blue"

colors[2]
#=>"green"

A hash looks like this:

fruit_colors = {"red" => "apple", "blue" => "blueberry", "green" => "lime"}

A hash has what we refer to key/value pairs. In this case, the values are “red”, “blue”, “green” and their values, respectively, are “apple”, “blueberry”, and “lime.”

Just like in the array example, if I wanted to return “lime”, I would call the key to get the value:

fruit_colors["green"]
#=>"lime"
    

Lets take a look at a hash with multiple values for one key:

fruit_colors = {"red" => ["apple", "strawberry"], "blue" => "blueberry", "green" => ["lime", "grape"]}

In this case, say I still want to get “lime”, I would need to get the values of green and then return the fruit by its index number, in this case “0”

fruit_colors["green"][0]
#=> "lime"

Without adding the array index, you would get back all the values of the key.

fruit_colors["red"]
#=>[
    [0] "apple",
    [1] "strawberry"
]

This was a pretty simple explanation, I’ll go into nested arrays and hashes next, but for more usage info, visit the ruby docs on arrays and hashes.