B.3 New Hash Syntax

Consider a Hash:

{ :fruit => "banana", :sport => "hockey" }

We can also (as of Ruby version 1.9) write the same thing as:

{ fruit: "banana", sport: "hockey" }

In other words, if the key in a key-value pair in a hash is a Symbol, you can move the colon (:) from the beginning of the symbol to the end of the symbol, and get rid of the hash rocket (=>). This is known as the “new hash syntax” (even though Ruby 1.9 is pretty old by now).

Consider the following Hash:

{ 1 => "pink", 2 => "cookies" }

Can we do the same trick and write this as:

{ 1: "pink", 2: "cookies" }

No! The “new” hash syntax is for when the keys are Symbols — then you can swing the Symbol’s colon around to the other side of it.