Hash vs Array


#1

Could someone explain the difference between a Hash and an Array? My understanding is a Hash is an Array, but an Array has keys numbering 0, 1, 2, 3 and a Hash can be numbered with anything Homer => Father instead in an Array Homer => 0.

Correct? I'm confused.


#2

The main difference is that arrays have to use integers as keys while hashes can use anything as keys. They're also two different types of objects, so a method could work on arrays and not on hashes or vice versa.

Also, they're members of different classes (you'll see about classes later in the course).


#3

An array is an ordered list with a numerical index. We can sort the members but not the index. Once sorted, members take the index of their new position in the array.

A hash is an unordered list in the form of an associative array. The index of the array is derived from the keys, which are associated with values in key=>value pairs.

This is a simple array of numbers:

var simple_nums = [ 1, 2, 3, 4, 5, 6, 7, 8 ]

At present, simple_nums[0] is 1, but if we reversed the array,

simple_nums.reverse!

simple_nums[0] is 8. The index is always ordered from 0.

This is a simple hash,

simple_hash = {
    key1 => 'value 1',
    key2 => 'value 2',
    key3 => 'value 3'
}

We can add to the hash,

simple_hash['newkey'] = 'new value'

We can see by the subscript that simple_hash is indeed an array, if but a special one. We cannot sort a hash unless we clone it to an actual array.

simple_hash_sorted = simple_hash.sort_by { |a,b| b }

simple_hash_sorted will be an array of arrays.