Hash Syntax Confusion
Learn about two types of Ruby syntaxes for defining a Hash object.
We'll cover the following
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:
{ one: "eins", two: "zwei", three: "drei" }
Using this syntax we tell Ruby that we want the keys to be symbols.
Hmmmm? We just learned that symbols are defined by prepending a word with a
colon like :one
, right?
Well, yes, correct, but that’s just how it works: If you define a hash using this syntax, then you’ll get a hash that has symbols as keys.
New syntax
The new syntax is confusing for beginners. It’s slightly less explicit and obvious, and you have to learn another piece of information.
Once you feel comfortable using hashes, you can make your own decision and start using the modern syntax if you prefer it.
In the meanwhile, whenever you see a hash using the new syntax somewhere else, you now know what it means and where to look it up. Simply remember that these two hashes are exactly the same:
puts hash = { :one => "eins", :two => "zwei", :three => "drei" }puts hash1 = { one: "eins", two: "zwei", three: "drei" }