Hash Syntax Confusion

Learn about two types of Ruby syntaxes for defining a Hash object.

You can skip the following and jump right to the next lesson if you’re already familiar with this topic, or you can keep reading if you’re curious. If you’re unfamiliar with the word syntax, you’ll benefit from reading this.

Many online resources use another alternative syntax to define hashes.

Note: The term syntax, in programming, refers to ways to use punctuation and other symbols to create objects (amongst other things).

The fact that we can use square brackets ([]) and commas (,) to define arrays, and curly braces ({}) and hash rockets (=>) to define hashes is part of Ruby’s syntax.

Two different syntaxes

Today, there are two different syntaxes to define hashes with curly braces, and they have the potential to confuse newcomers a lot.

We use the old syntax and ignore the new one, for now. Next, we’ll discuss why.

Old syntax

Up to a certain version of Ruby, the syntax that used hash rockets was the only syntax to create hashes, and it works the same for all hashes no matter what kinds of objects we use as keys.

Then, a few years back, a new syntax was introduced. Many Ruby programmers love to use it, because it takes a little less space, and it also looks a lot like JSON, which is a data format that is widely used in web applications.

The new hash syntax looks like this:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy