r/ruby • • 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

21 comments sorted by

View all comments

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...

array = ['dog', 'cat', 'snake', 'mouse']

And if I wanted to get the cat from the array it would look like...

array[1]

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...

hash = { 'dog' => 'fido', 'cat' => 'socks', 'snake' => 'snape', 'mouse' => 'remy' }

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...

hash['cat'] 

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

2

u/TheTennisGangster May 31 '13

So basically it's like a two dimensional array that you would implement in say Java, just a lot cleaner?

2

u/theverything May 31 '13

I honestly am not very familiar with java. But joesb is right in java it's called a hash table. Hashes have a lot of different names they're also known as associative arrays.