Credit: Ben Giddings
Problem
When using a hash, you want the slight optimization you can get by using symbols as keys instead of strings.
Solution
Whenever you would otherwise use a quoted string, use a symbol instead. A symbol can be created by either using a colon in front of a word, like :keyname, or by transforming a string to a symbol using String#intern.
people = Hash.new people[:nickname] = 'Matz' people[:language] = 'Japanese' people['last name'.intern] = 'Matsumoto' people[:nickname] # => "Matz" people['nickname'.intern] # => "Matz"
Discussion
While 'name' and 'name' appear exactly identical, they're actually different. Each time you create a quoted string in Ruby, you create a unique object. You can see this by looking at the object_id method.
'name'.object_id # => -605973716 'name'.object_id # => -605976356 'name'.object_id # => -605978996
By comparison, each instance of a symbol refers to a single object.
:name.object_id # => 878862 :name.object_id # => 878862 'name'.intern.object_id # => 878862 'name'.intern.object_id # => 878862
Using symbols instead of strings saves memory and time. It saves memory because there's only one symbol instance, instead of many string instances. If you have many hashes that contain the same keys, the memory savings adds up.
Using symbols as hash keys is faster because the hash value of a symbol is simply its object ID. If you use strings in a hash, Ruby must calculate the hash value of a string each time it's used as a hash key.
See Also
Strings
Numbers
Date and Time
Arrays
Hashes
Files and Directories
Code Blocks and Iteration
Objects and Classes8
Modules and Namespaces
Reflection and Metaprogramming
XML and HTML
Graphics and Other File Formats
Databases and Persistence
Internet Services
Web Development Ruby on Rails
Web Services and Distributed Programming
Testing, Debugging, Optimizing, and Documenting
Packaging and Distributing Software
Automating Tasks with Rake
Multitasking and Multithreading
User Interface
Extending Ruby with Other Languages
System Administration