Storing Data: arrays vs. hashes

Clash of the titans

June 26th, 2015

Time is flying by! Already week 3 of Phase 0 coming to an end! Week 1 was all about Git, GitHub and getting comfy with the command line. HTML & CSS were running the show during week 2, but things got more back-end this week with an introduction to Ruby.
The Ruby language has been around since the '90s and is often considered to be the most elegant, human-friendly and powerful. Great websites and platforms such as Shopify, SoundCloud and GitHub are built on Ruby! One of the most important aspect of the language is in how data and information is stored. Storing and managing data properly is crucial, SoundCloud features millions of songs, without a proper back-end we couldn't hear what we want so easily. At the heart of storing data: arrays and hashes.

Arrays and hashes both serve the same purpose: storing information. In Ruby we talk about 'objects', so arrays and hashes can store any kind of objects: strings, integers and even arrays. In both cases objects are indexed with a key, meaning they can be accessed using a key.

Arrays

An array is the simplest way to store objects, they are always indexed by integers, ordered in numerical order. See below:

array = [1, 'cat', [23, 'coin-coin']]   # arrays always use square brackets

# access the second element by calling it using the integer
# note that the first element starts with 0

puts array [1]
'cat'


# how to create a new array

new-array = ['coin-coin']

Hashes

Hashes are a little more elaborated and offer more flexibility, instead of being indexed by integers, they can be indexed using any kind of object, such as strings. The applications are endless, imagine you want to store a list of songs based on the artists profile, it would look something like this:

hash = {                                            # hashes use braces
    :'Boy Boy Boy' => 'Andhim'
    :'Sympathy For The Devil' => 'The Rolling Stones'
    :'Hausch' => 'Andhim'
    :'Nemesis' => 'Benjamin Clementine'
    :'Lady Jane' => 'The Rolling Stones'
}

# values can be accessed using square brackets

puts hash[ 'Lady Jane' ]
'The Rolling Stones'



# how to create a new hash

songs = Hash.new
songs[:'song a'] = 'artist a'
songs[:'song b'] = 'artist b'

Put simply: an array is a simpler version of a hash, since it can only be indexed using integers. I'm excited to start using these tools and get a deeper understanding of their real-life applications! As usual, feedback is more than welcome!