Rather than using Strings as the keys in a Hash, it's better practice to use Symbols.
Symbols is just like Strings except they ' re faster and take to less memory. The reason Symbols is, efficient is, and the They is immutable; They cannot is changed, so Ruby doesn ' t has to allocate as much memory. Strings on the other hand, can is changed, so Ruby allocates more memory to allow for that. If you want a further thorough explanation of why they is faster, check out the This blog post.
Let's try using them as keys in a Hash. Here's a version of a Hash that uses Strings as keys:
Kitten = { "name""Blue Steele", " Breed " " Scottish Fold " , " Age " " weeks " }
We can rewrite it using Symbols:
Kitten = { "Blue Steele", "Scottish Fold " , " weeks " }
Aside from the slight performance boost, another good reason to use Symbols are that Ruby 1.9 introduced a "shortcut" Synta X for declaring hashes with Symbols as keys. We could rewrite the above Hash as:
Kitten = { "Blue Steele", "Scottish Fold " , " weeks " }
It saves us have to type those annoying hash rockets ( =>
), and it closely models the syntax of other languages like Javascript.
To wrap up, it's a good idea to use Symbols as keys in a Hash because they ' re slightly faster than Strings, and Ruby provi Des us a nice shortcut syntax.
Why we use the Symbols in Hash