Thursday, May 17, 2012

What are hashes in ruby, and how are they different from regular hash tables?

A hash in ruby is basically a regular hash table with some cool added features. That is, it's a data structure that maps keys of any type (string, integer, mostly symbol, etc) to values (of not necessarily the same type).

Do define a hash in ruby, you type something like this: h = {:username => 'john302', :password => 'coolstuff', :age => 5}. Then to access the value stored with key :username, you would say h[:username], which in this example would evaluate to the string john302.

To define an empty hash, you can say h = {} or h = Hash.new (or h = Hash.new()).

The reason they're different from regular hash tables is you can define cool things like default values. For example, say you want a hash where an integer maps to its cube. You can type h = Hash.new({|hash, key| hash[key] = key * key * key}). This sets the default value of, say, h[5] to 125. I am pretty sure they use something akin to streams to do this. It's really interesting. Anyway, you can still store something in the hash, like, say, h[5] = 'cat', but if nothing is stored in a slot in the hash, it will default to its default value.

I think that the time it takes to do this is dependent on the function, though. For example, if you have a function that adds a key to itself a hundred times, mapping that function as the default for a hash will take a tiny amount of time. But computing a default value will actually do the work (add the key to itself a hundred times), so it may be slower. So hashes in ruby are not magic.

The really interesting thing is that this doesn't only work with integers. For example, if you say h = Hash.new {|hash,key| hash[key] = key + key}, then h['cat'] will default to 'catcat'. You have to be careful though, because not every operation is defined for every type. e.g., you shouldn't say h = Hash.new {|hash,key| hash[key] = key / key}, because then trying to say h[5] will evaluate to 1, but h['cat'] will raise a NoMethodError.

You can find out the other cool stuff about hashes at the documentation page on them.

So, that's what hashes are in ruby, and how they're different from regular hash tables.

No comments:

Post a Comment