Last Updated: February 25, 2016
·
652
· we4tech

Ruby Symbols (MRI). they are EVERYWHERE! even :| a symbol.

There was a discussion in local ruby group Rubyist. To get the real answer where and how ruby Symbols are stored and so on around. I dug through ruby source to figure out what is actually happening underneath.

Actually this is the main struct which holding up all symbols -

Ruby source from Github

static struct symbols {
  ID last_id;
  st_table *sym_id;
  st_table *id_str;
#if ENABLE_SELECTOR_NAMESPACE
  st_table *ivar2_id;
  st_table *id_ivar2;
#endif
  VALUE op_sym[tLAST_OP_ID];
} global_symbols = {tLAST_TOKEN};

Whatever you write in your ruby. ie. Variable name, $global_variable, Class name, method name or even CONSTANT everything turns into Symbol and added to this list.

Moreover it's defined in grammer (As you saw it in parse.y) and thus it's actually initiated when ":Something" syntax is used and parsed through parser.

So whenever parser kicks off symbol get's populated thus Azharul Islam was surprised when he got Symbol.all.include?(:something_none_existing) => true

Fyi,

Ruby source from Github

This is the original code behind 'Symbol.all_symbols'

rb_sym_all_symbols(void)
{
  VALUE ary = rb_ary_new2(global_symbols.sym_id->num_entries);

  st_foreach(global_symbols.sym_id, symbols_i, ary);
  return ary;
}

:)