Understanding Ruby Symbols

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.

One More Reason to Avoid Ruby Language

Ruby is type unsafe language but it goes a step further and avoids checking dynamically too.

Consider this code

x = :abc
if x == 'abc'
  puts "Symbol and String are two different classes"
  puts x.class, 'abc'.class

# puts can print a symbol and string alike.
puts x

My Complaints

  • I’m new to Ruby. How could Ruby let a Symbol and String compare, in spite of being aware of their types? Like Python, it can throw an error.
  • How can puts print a Symbol as good as a String