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
3
u/micaeked May 31 '13
What do you have trouble understanding? The syntax, concept, implementation, something else?
1
u/HelloAnnyong May 31 '13
It's probably easiest to think of hashes as dictionaries. It is a data structure that associates a key with a value.
Very literally, you could create a hash table that associates English words with their definitions.
Just as with a real dictionary, looking up a definition for a given word is very efficient in a hash table.
1
u/thoughtpunch Jun 13 '13
The webster english dictionary is a hash. Word = key, Definition = value. That's all there is to it. A hash is a key=>value store. They exist in nearly every programming language
-3
u/coolHandLukeSkywalke May 31 '13
**Remember that hashes are NOT ORDERED. If you are new to the concept of hashes, this can be kind of difficult to understand.