Arrays vs Hashes

When to use each

April 25, 2015

Arrays are ordered collections of objects, be it strings, numbers, or arrays themselves! Hashes are collections, too, but they're unordered and utilize key-value pairs.

In Ruby, you can initialize arrays with the new method or implicitly, by populating them

ingredients =
ingredients = ["shrimp", "cumin", "chicken", "avocado", "cilantro"]
players = ["Joakim Noah", "Nate Robinson", "Tim Duncan", "Paul Pierce"]

Arrays are indexed by integers, starting at 0. If you wanted to access "Nate Robinson" from the players array, you would do it like so:


Ruby has really convenient class methods for Arrays. You can access the first or last element of an array easily by calling (whatever's after the # symbol is just a comment in Ruby. I just want to show you what will be returned from the method):

ingredients.first #=> "shrimp" 
ingredients.last #=> "cilantro" 

You can even return the first n elements of an array:

ingredients.take(2) #=> ["shrimp", "cumin"]

Arrays can also be counted easily or checked for emptiness by:

ingredients.length #=> 5
ingredients.count #=> 5
ingredients.empty? #=> false

Let's move on to hashes for now. While arrays are awesome at keeping your elements organized, hashes are great for a different type of organization. Instead of using integers to access your values, you can use any object type to do so. For example, let's initialize a hash called population. We'll initialize it implicitly, without the "new" keyword.

population = {"Tiny Farm Town" => 1,000, "Suburban" => 20,000, 
"Gentrified Brooklyn" => 1,000,000}

You can also use what are called symbols as the keys. Symbols are preceded with a colon. You still use "#=>" to point to your value, like so:

population = { :tiny_farm => 1,000}

Or you can do this and forget about the "=>":

population = { tiny_farm: 1000, suburban: 20,000, gentrified_brooklyn:

You can populate a Hash differently, one by one, like this:

cities = {}
cities[:san_diego] = "college"
cities[:los_angeles] = "home"

You can use hashes as named parameters in a method. This might be beyond the scope of this beginner post, but I thought it was pretty cool:

Employee.create(name: "Blake Griffin", age: 25)

I think that's all I have for now. Til next time! Thanks for reading.