Ruby for Programmers – Part 7: Hash

Last up on the major built-in classes in the Hash, look at how you can organize random bits of data:

It lets you organize data to carry with you. The hash rocket way of making an array allows you to use anything, the colon/JSON way uses Symbols:

Most of the time, your Hashs will use Symbols (the fat-free String) to pass things around. This is very common in Rails that accepts multiple kinds of options in a single function.

You can create a default for a Hash on creation, which might be useful for various operations:

Notice how it could sum up how many of which kind? We’ll be making lots of hashes later on to move data around.

As always, check the docs page of all the things you can do to a Hash.

Something else to note, Hash is an Enumerable too, so you can use #each and #detect them. Some though, depends on the version of Ruby what comes out. The following example is from 2.1.0-p0, the latest version (as of writing):

Notice how some functions, like #each and #detect, will return an array but #select will return a Hash? So be aware of which functions returns Hashes and which return Arrays. And another trick, if you use two variables in the block, then it will instead be key, value respectively: