Arrays and Hashes: What's the dealio?

A quick run-down on the similarities and differences

January 31st, 2015 : 1 minute

What do arrays and hashes have in common?

Both arrays and hashes are used to store data.They are indexed collections of objects that are accessible using a key. They can both hold objects of different types (ie. integers, strings, floating numbers).

What do arrays and hashes not have in common?

Arrays are indexed by number whereas in hashes, any arbitrary object can be the key/index.

Imagine a coat check. You give them you coat, and you get a number. In order to retrieve your coat, you have to bring them the "key" that has the corresponding number. This is like an array.

Hashes on the other hand offer more flexibility (and therefore a wider scope) when it comes to indexing. Instead of by number, hashes store key-value pairs of any kind. To follow the coat check example, instead of just indexing each coat by number, they could store coats by your name, or the brand of the coat, or the color of the coat, or how expensive your coat is. The options are endless.