Ruby is an interpreted language. It is dynamically typed and uses a new memory for a variable. A variable has a name and a value. Symbols are an optimized variable that holds single instance of memory. It is good for variables that assume the same values across the program such as hash table keys.
h = {'my_key' => 123}
The storage for my_key
is allocated each time my_key
is used. That’s waste of memory and many related bookkeeping tasks by the Ruby interpreter.
So declaring the key as a symbol makes sense as only one copy of my_key
is kept in memory.
h = {:my_key => 123}
You have to use the :
operator with each usage of a symbol.
irb(main):003:0> new_hash={:my_key => 123}
=> {:my_key=>123}
irb(main):004:0> new_hash[:my_key]
=> 123
# You must use the :
irb(main):005:0> new_hash[my_key]
NameError: undefined local variable or method `my_key' for main:Object
from (irb):5
irb(main):006:0> new_hash['my_key']
=> nil
Written with StackEdit.