Methods of Hash Class

Learn different methods of the hash class.

Hash in JavaScript

In general, the hash data structure is pretty straightforward. Ruby has some methods of the Hash class that we will probably see in other languages as well. Here is, for example, what hash access looks like in JavaScript:

$ node
> hh = {};
{}
> hh['something'] = 'blabla';
'blabla'
> hh
{ something: 'blabla' }

The difference is that JavaScript doesn’t have a symbol type, and most of the time strings are used as hash keys. We can see a comparison between Ruby and JavaScript below.

Hash in Ruby

We can also use:

hh[:something]

or (also valid syntax):

hh['something']

Below is what JavaScript looks like:

hh['something']

Hash in Redis

Hash is the data structure that is also implemented in other tools like databases. The well-known Redis database is nothing but sophisticated key-value storage. In previous lessons, we’ve implemented a phone book. But imagine that we need this data to persist on application restart. We have a couple of ways to do that. For example, we can save, or serialize, this information into a file. This approach works great, but it can be a little bit slow when we have millions of records. Another approach is to use a NoSQL database, central storage operated by Redis through an API (Application Program Interface).

It doesn’t matter what exactly we’re using—a library, a gem, a database, or plain old Ruby language—,the interface for hash access remains the same:

  • get(key): gets the value
  • set(key, value): sets the value for a specific key

Documentation for Redis database has similar example:

redis.set("mykey", "hello world")
#=> "OK"
redis.get("mykey")
#=> "hello world"

A curious learner might ask, “Why do we need Redis when we have a hash data structure implemented in Ruby, represented by the Hash class?” Hash in Ruby doesn’t keep the data on disk, so every time we restart our program, all the data stored in the hash goes away. For example, the phone book application isn’t very useful because of that. We can keep the program running, but if we need to restart our computer we’ll need to type in our phone records again. The second reason is that Redis was designed to keep millions and millions of key-value pairs efficiently. Normally, we don’t keep that number of records in a simple hash in Ruby or any other language.

Get hands-on with 1200+ tech skills courses.