Ruby - Module Symbol Table

Introduction

A symbol is a pointer into the symbol table.

The symbol table is Ruby's internal list of known identifiers-such as variable and method names.

You can display all the symbols that Ruby knows about like this:

p( Symbol.all_symbols )

This will shows thousands of symbols including method names such as :to_s and :reverse.

It will also show global variables such as :$/ and :$DEBUG, and class names such as :Array and :Symbol.

You may restrict the number of symbols displayed using array indexes like this:

Demo

p( Symbol.all_symbols[0,10] )

Result

In Ruby 1.8, you can't sort symbols.

In Ruby 1.9, sorting is possible, and the symbol characters are sorted as though they were strings:

Demo

# In Ruby 1.9
p [:a,:c,:b].sort          #=> [:a,:b,:c]
# In Ruby 1.8# ww w. jav  a 2 s .  co  m
p [:a,:c,:b].sort       #=> 'sort': undefined method '<=>' for :a:Symbol

Result

You can convert the symbols to strings and sort those.

str_arr = Symbol.all_symbols.collect{ |s| s.to_s }
puts( str_arr.sort )

Related Topic