class Symbol

ASymbol object represents a named identifier inside the Ruby interpreter.

You can create aSymbol object explicitly with:

The sameSymbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus ifFred is a constant in one context, a method in another, and a class in a third, theSymbol:Fred will be the same object in all three contexts.

moduleOneclassFredend$f1 =:FredendmoduleTwoFred =1$f2 =:FredenddefFred()end$f3 =:Fred$f1.object_id#=> 2514190$f2.object_id#=> 2514190$f3.object_id#=> 2514190

Constant, method, and variable names are returned as symbols:

moduleOneTwo =2defthree;3end@four =4@@five =5$six =6endseven =7One.constants# => [:Two]One.instance_methods(true)# => [:three]One.instance_variables# => [:@four]One.class_variables# => [:@@five]global_variables.grep(/six/)# => [:$six]local_variables# => [:seven]

ASymbol object differs from aString object in that aSymbol object represents an identifier, while aString object represents text or data.

What’s Here

First, what’s elsewhere. ClassSymbol:

Here, classSymbol provides methods that are useful for:

Methods for Querying

Methods for Comparing

Methods for Converting

Public Class Methods

Source
static VALUEsym_all_symbols(VALUE _){    return rb_sym_all_symbols();}

Returns an array of all symbols currently in Ruby’s symbol table:

Symbol.all_symbols.size# => 9334Symbol.all_symbols.take(3)# => [:!, :"\"", :"#"]
Source
# File ext/json/lib/json/add/symbol.rb, line 49defself.json_create(o)o['s'].to_symend

Seeas_json.

Public Instance Methods

Source
static VALUEsym_cmp(VALUE sym, VALUE other){    if (!SYMBOL_P(other)) {        return Qnil;    }    return rb_str_cmp_m(rb_sym2str(sym), rb_sym2str(other));}

Ifobject is a symbol, returns the equivalent ofsymbol.to_s <=> object.to_s:

:bar<=>:foo# => -1:foo<=>:foo# => 0:foo<=>:bar# => 1

Otherwise, returnsnil:

:foo<=>'bar'# => nil

Related:String#<=>.

Source
#define sym_equal rb_obj_equal

Returnstrue ifobject is the same object asself,false otherwise.

Also aliased as:===
Alias for:==
Source
static VALUEsym_match(VALUE sym, VALUE other){    return rb_str_match(rb_sym2str(sym), other);}

Equivalent tosymbol.to_s =~ object, including possible updates to global variables; seeString#=~.

Source
static VALUEsym_aref(int argc, VALUE *argv, VALUE sym){    return rb_str_aref_m(argc, argv, rb_sym2str(sym));}

Equivalent tosymbol.to_s[]; seeString#[].

Also aliased as:slice
Source
# File ext/json/lib/json/add/symbol.rb, line 23defas_json(*)  {JSON.create_id=>self.class.name,'s'=>to_s,  }end

MethodsSymbol#as_json andSymbol.json_create may be used to serialize and deserialize a Symbol object; seeMarshal.

MethodSymbol#as_json serializesself, returning a 2-element hash representingself:

require'json/add/symbol'x =:foo.as_json# => {"json_class"=>"Symbol", "s"=>"foo"}

MethodJSON.create deserializes such a hash, returning a Symbol object:

Symbol.json_create(x)# => :foo
Source
static VALUEsym_capitalize(int argc, VALUE *argv, VALUE sym){    return rb_str_intern(rb_str_capitalize(argc, argv, rb_sym2str(sym)));}

Equivalent tosym.to_s.capitalize.to_sym.

SeeString#capitalize.

Source
static VALUEsym_casecmp(VALUE sym, VALUE other){    if (!SYMBOL_P(other)) {        return Qnil;    }    return str_casecmp(rb_sym2str(sym), rb_sym2str(other));}

LikeSymbol#<=>, but case-insensitive; equivalent toself.to_s.casecmp(object.to_s):

lower =:abcupper =:ABCupper.casecmp(lower)# => 0lower.casecmp(lower)# => 0lower.casecmp(upper)# => 0

Returns nil ifself andobject have incompatible encodings, or ifobject is not a symbol:

sym ='äöü'.encode("ISO-8859-1").to_symother_sym ='ÄÖÜ'sym.casecmp(other_sym)# => nil:foo.casecmp(2)# => nil

UnlikeSymbol#casecmp?, case-insensitivity does not work for characters outside of ‘A’..‘Z’ and ‘a’..‘z’:

lower =:äöüupper =:ÄÖÜupper.casecmp(lower)# => -1lower.casecmp(lower)# => 0lower.casecmp(upper)# => 1

Related:Symbol#casecmp?,String#casecmp.

Source
static VALUEsym_casecmp_p(VALUE sym, VALUE other){    if (!SYMBOL_P(other)) {        return Qnil;    }    return str_casecmp_p(rb_sym2str(sym), rb_sym2str(other));}

Returnstrue ifself andobject are equal after Unicode case folding, otherwisefalse:

lower =:abcupper =:ABCupper.casecmp?(lower)# => truelower.casecmp?(lower)# => truelower.casecmp?(upper)# => true

Returns nil ifself andobject have incompatible encodings, or ifobject is not a symbol:

sym ='äöü'.encode("ISO-8859-1").to_symother_sym ='ÄÖÜ'sym.casecmp?(other_sym)# => nil:foo.casecmp?(2)# => nil

UnlikeSymbol#casecmp, works for characters outside of ‘A’..‘Z’ and ‘a’..‘z’:

lower =:äöüupper =:ÄÖÜupper.casecmp?(lower)# => truelower.casecmp?(lower)# => truelower.casecmp?(upper)# => true

Related:Symbol#casecmp,String#casecmp?.

Source
static VALUEsym_downcase(int argc, VALUE *argv, VALUE sym){    return rb_str_intern(rb_str_downcase(argc, argv, rb_sym2str(sym)));}

Equivalent tosym.to_s.downcase.to_sym.

SeeString#downcase.

Related:Symbol#upcase.

Source
static VALUEsym_empty(VALUE sym){    return rb_str_empty(rb_sym2str(sym));}

Returnstrue ifself is:'',false otherwise.

Source
static VALUEsym_encoding(VALUE sym){    return rb_obj_encoding(rb_sym2str(sym));}

Equivalent toself.to_s.encoding; seeString#encoding.

Source
static VALUEsym_end_with(int argc, VALUE *argv, VALUE sym){    return rb_str_end_with(argc, argv, rb_sym2str(sym));}

Equivalent toself.to_s.end_with?; seeString#end_with?.

Alias for:to_s
Source
static VALUEsym_inspect(VALUE sym){    VALUE str = rb_sym2str(sym);    const char *ptr;    long len;    char *dest;    if (!rb_str_symname_p(str)) {        str = rb_str_inspect(str);        len = RSTRING_LEN(str);        rb_str_resize(str, len + 1);        dest = RSTRING_PTR(str);        memmove(dest + 1, dest, len);    }    else {        rb_encoding *enc = STR_ENC_GET(str);        VALUE orig_str = str;        len = RSTRING_LEN(orig_str);        str = rb_enc_str_new(0, len + 1, enc);        // Get data pointer after allocation        ptr = RSTRING_PTR(orig_str);        dest = RSTRING_PTR(str);        memcpy(dest + 1, ptr, len);        RB_GC_GUARD(orig_str);    }    dest[0] = ':';    RUBY_ASSERT_BUILTIN_TYPE(str, T_STRING);    return str;}

Returns a string representation ofself (including the leading colon):

:foo.inspect# => ":foo"

Related:Symbol#to_s,Symbol#name.

Alias for:to_sym
Source
static VALUEsym_length(VALUE sym){    return rb_str_length(rb_sym2str(sym));}

Equivalent toself.to_s.length; seeString#length.

Also aliased as:size
Source
static VALUEsym_match_m(int argc, VALUE *argv, VALUE sym){    return rb_str_match_m(argc, argv, rb_sym2str(sym));}

Equivalent toself.to_s.match, including possible updates to global variables; seeString#match.

Source
static VALUEsym_match_m_p(int argc, VALUE *argv, VALUE sym){    return rb_str_match_m_p(argc, argv, sym);}

Equivalent tosym.to_s.match?; seeString#match.

Source
# File symbol.rb, line 26defnamePrimitive.attr!:leafPrimitive.cexpr!'rb_sym2str(self)'end

Returns a frozen string representation ofself (not including the leading colon):

:foo.name# => "foo":foo.name.frozen?# => true

Related:Symbol#to_s,Symbol#inspect.

Equivalent toself.to_s.succ.to_sym:

:foo.succ# => :fop

Related:String#succ.

Alias for:succ
Alias for:length
Alias for:[]
Source
static VALUEsym_start_with(int argc, VALUE *argv, VALUE sym){    return rb_str_start_with(argc, argv, rb_sym2str(sym));}

Equivalent toself.to_s.start_with?; seeString#start_with?.

Source
static VALUEsym_succ(VALUE sym){    return rb_str_intern(rb_str_succ(rb_sym2str(sym)));}

Equivalent toself.to_s.succ.to_sym:

:foo.succ# => :fop

Related:String#succ.

Also aliased as:next
Source
static VALUEsym_swapcase(int argc, VALUE *argv, VALUE sym){    return rb_str_intern(rb_str_swapcase(argc, argv, rb_sym2str(sym)));}

Equivalent tosym.to_s.swapcase.to_sym.

SeeString#swapcase.

Source
# File ext/json/lib/json/add/symbol.rb, line 39defto_json(state =nil,*a)state =::JSON::State.from_state(state)ifstate.strict?superelseas_json.to_json(state,*a)endend

Returns aJSON string representingself:

require'json/add/symbol'puts:foo.to_json

Output:

# {"json_class":"Symbol","s":"foo"}
Calls superclass method
Source
VALUErb_sym_to_proc(VALUE sym){    enum {SYM_PROC_CACHE_SIZE = 67};    if (rb_ractor_main_p()) {        if (!sym_proc_cache) {            sym_proc_cache = rb_ary_hidden_new(SYM_PROC_CACHE_SIZE);            rb_ary_store(sym_proc_cache, SYM_PROC_CACHE_SIZE - 1, Qnil);        }        ID id = SYM2ID(sym);        long index = (id % SYM_PROC_CACHE_SIZE);        VALUE procval = RARRAY_AREF(sym_proc_cache, index);        if (RTEST(procval)) {            rb_proc_t *proc;            GetProcPtr(procval, proc);            if (proc->block.as.symbol == sym) {                return procval;            }        }        procval = sym_proc_new(rb_cProc, sym);        RARRAY_ASET(sym_proc_cache, index, procval);        return RB_GC_GUARD(procval);    }    else {        return sym_proc_new(rb_cProc, sym);    }}

Returns aProc object which calls the method with name ofself on the first parameter and passes the remaining parameters to the method.

proc =:to_s.to_proc# => #<Proc:0x000001afe0e48680(&:to_s) (lambda)>proc.call(1000)# => "1000"proc.call(1000,16)# => "3e8"(1..3).collect(&:to_s)# => ["1", "2", "3"]
Source
# File symbol.rb, line 10defto_sPrimitive.attr!:leafPrimitive.cexpr!'rb_sym_to_s(self)'end

Returns a string representation ofself (not including the leading colon):

:foo.to_s# => "foo"

Related:Symbol#inspect,Symbol#name.

Also aliased as:id2name
Source
# File symbol.rb, line 37defto_symselfend

Returnsself.

Related:String#to_sym.

Also aliased as:intern
Source
static VALUEsym_upcase(int argc, VALUE *argv, VALUE sym){    return rb_str_intern(rb_str_upcase(argc, argv, rb_sym2str(sym)));}

Equivalent tosym.to_s.upcase.to_sym.

SeeString#upcase.