Rather than using Strings as the keys in a Hash, it’s better practice to use Symbols.
Symbols are just like Strings except they’re faster and take up less memory. The reason Symbols are so efficient is that they are immutable; they cannot be changed, so Ruby doesn’t have to allocate as much memory. Strings on the other hand, can be changed, so Ruby allocates more memory to allow for that. If you want a more thorough explanation of why they are faster, check out 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" => "13 weeks" }
We can rewrite it using Symbols:
kitten = { :name => "Blue Steele", :breed => "Scottish Fold", :age => "13 weeks" }
Aside from the slight performance boost, another good reason to use Symbols is that Ruby 1.9 introduced a “shortcut” syntax for declaring Hashes with Symbols as keys. We could rewrite the above Hash as:
kitten = { name: "Blue Steele", breed: "Scottish Fold", age: "13 weeks" }
It saves us having 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 provides us a nice shortcut syntax.