Arrays vs Hashes in Ruby

Why use one versus the other? First let's start with the ways in which the two are similar. They are both indexed collections that store objects, which can be accessed using a key. For hashes, that key can be anything including another object; while for arrays the key is an integer reflecting the objects position in the array. So as you can tell, they have quite a lot in common with the key difference being what consitutes a key.

The flexibility of the using any object as a key for hashes can be quite helpful. To employ an oft used example, if you have a menu with items and prices, you can think of the item as the key and the price as the object to be retrieved. You could achieve a similar result in a variety of ways with an array, but it would be a lot messier and take more work and who wants that? Anyways, I'm feeling tired, it's late in the afternoon and would love a coffee. I wonder what it costs?

menu = {
    'coffee' => 8.00,
    '3 wishes' => 2.00,
    'fig pig sandwich' => 4.45,
    'espresso' => 9.00,
}

menu['coffee']        # returns $8

$8! Thanks, but I'll stick with instant. The wishes on the other hand look like a bargain...


For more on hashes, check out Ruby Monk. And to learn some Ruby shortcuts, including some for arrays, go here.