David Walden

Arrays and Hashes

March 6, 2016

What are the differences between arrays and hashes? Why would you use one over the other?

Arrays and hashes are both structured like lists and every slot in the list acts like a variable. Each slot points to a particular object. Arrays are indexed with numbers that start with 0 and go up to the array’s length minus one. Hashes are collections of key-value pairs. You would use a hash if you don’t want to use numbers as indices or if you want to use unordered numeric indices. With a hash, you can use any Ruby object for a key or value.

To create an array use the following syntax:

              array = [value1, value2, value3]
            

To create a hash use the following syntax:

              hash = { :key1 => value1, :key2 => value2, :key3 => value3 }