public Method

String.intern

str.intern    symbol
str.to_sym    symbol

Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name.

"Koala".intern         #=> :Koala
s = 'cat'.to_sym       #=> :cat
s == :cat              #=> true
s = '@cat'.to_sym      #=> :@cat
s == :@cat             #=> true

This can also be used to create symbols that cannot be represented using the :xxx notation.

'cat and dog'.to_sym   #=> :"cat and dog"

Source Code

/*
*  call-seq:
*     str.intern   => symbol
*     str.to_sym   => symbol
*  
*  Returns the <code>Symbol</code> corresponding to <i>str</i>, creating the
*  symbol if it did not previously exist. See <code>Symbol#id2name</code>.
*     
*     "Koala".intern         #=> :Koala
*     s = 'cat'.to_sym       #=> :cat
*     s == :cat              #=> true
*     s = '@cat'.to_sym      #=> :@cat
*     s == :@cat             #=> true
*
*  This can also be used to create symbols that cannot be represented using the
*  <code>:xxx</code> notation.
*     
*     'cat and dog'.to_sym   #=> :"cat and dog"
*/

VALUE
rb_str_intern(s)
   VALUE s;
{
   volatile VALUE str = s;
   ID id;

   if (!RSTRING(str)->ptr || RSTRING(str)->len == 0) {
       rb_raise(rb_eArgError, "interning empty string");
   }
   if (strlen(RSTRING(str)->ptr) != RSTRING(str)->len)
       rb_raise(rb_eArgError, "symbol string may not contain `\\0'");
   if (OBJ_TAINTED(str) && rb_safe_level() >= 1 && !rb_sym_interned_p(str)) {
       rb_raise(rb_eSecurityError, "Insecure: can't intern tainted string");
   }
   id = rb_intern(RSTRING(str)->ptr);
   return ID2SYM(id);
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.