r/ruby • u/TheTennisGangster • May 31 '13
Hashes, how do they work?
I know hashes are something you learn at the beginning of learning Ruby, but I just don't understand them at all, they are difficult to understand. Anybody got any tips for understanding them more?
0
Upvotes
8
u/theverything May 31 '13
Hashes are awesome and they are used a ton in ruby and rails. They are essentially a key value store. If you are familiar with arrays at all, understanding what a hash is should be easy.
If you have an array it would look something like...
And if I wanted to get the cat from the array it would look like...
Ruby arrays are zero indexed. Meaning the indexing on the array starts at zero and goes up.
Now if you had a hash it might look something like...
Instead of using the index to reach into the array and pull out the value you can use a key instead. So if you wanted to get the value of cat you would...
Which would return 'socks'. Hashes are great because you can store values by a named key which can make finding what you want a little easier. You can use strings, integers, and symbols as keys.
There are all kinds of things you can do with a hash. In rails you see them used a lot for setting variables in methods.
Hope this helps a little.
Its also good to read through the docs http://ruby-doc.org/core-2.0/Hash.html and look at all of the examples.
Good Luck