Problems with Hashes


Hi everyone, actually I'm having difficulties to understand what hashes are and how they work.
I'm doing the exercises but I'm not realizing what's is going on with the code.


Hashes are simply a collection of elements. Each of these elements is defined by a key and a value.

An example of usage could be if you had locations and coordinates, you would want each location as keys, and coordinates as values, so that when you ask for a location you get the corresponding coordinates. That's only an example, if you keep programming you'll understand really how hashes can be useful.


So that's the problem. Hashes are a kind of variable, right? BUT what I can not understand is the difference between hashes and arrays. I get that with array I can make a multidimensional array. I mean, which one would be better to use in a code and make it working better? 'Cause until now, both are same to me


The difference between a hash and an array is that the array has default keys (integers starting from 0), while the hash has arbitrary keys.

You could very well decide to use a 2 dimensional array instead of a hash, but it would mean that you would need to access the data from the same usual indexes (for example array[0][0] for the first key and array[0][1] for the first value).
Besides the fact that it's a bit less convenient, it also prevents the association of the two datas, you cannot access the values with the names of the keys anymore, you're forced to use integers for both.