Jan Dennison

Harrays and Ashes: Keeping Your Ruby Sorted

Jan 11, 2015

Hashes and Arrays in Ruby

As in JavaScript, Ruby provides ways to store information in groups to reference later. These ways include Arrays and Hashes, which are similar in purpose but vary in structure. Let's take a closer look at each.

Arrays

Arrays are collections of data that are list-like; that is, each item is numbered and follow the one prior, much like an ordered list<ol> in HTML. Arrays are needed because without them, we only have the ability to assign one item to a variable:
best_icecream = "Rocky Road"
Arrays let us add lots of items though, and keeps them grouped together:
best_icecreams = ["Rocky Road", "Cookie Dough", "Cherry Garcia"]
Square brackets [ ] indicate an array grouping. Items in the array are numbered, or indexed (starting at 0, not 1). Thus, to access individual items in an array, you just refer to the index value:
best_icecreams[0] #returns Rocky Road
best_icecreams[1] #returns Cookie Dough
best_icecreams[2] #returns Cherry Garcia

Hashes

If arrays are like HTML ordered lists, hashes are the counterpart, unordered lists <ul>. But instead of a number to designate items (or bullet points), you assign your own labels, or keys. The item you assign to the key in the list is called a value. Hashes, therefore, are much like JavaScript objects consisting of key:value pairs.

    best_icecreams = {
      "chocolate" = "Double Dutch Fudge",
      "cookie" = "Oreo blizzard",
      "fruity" = "Strawberry"
     }
As you can see, being able to label each item rather than just numbering adds in extra information that can be useful. You can identify "Which is the best chocolate icecream?" by just calling:
best_icecreams["chocolate"]
Hashes are indicated by curly brackets { }.