123456789_123456789_123456789_123456789_123456789_

Class: Symbol

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
self, ::Comparable
Inherits: Object
Defined in: string.c,
string.c

Overview

Symbol objects represent named identifiers inside the Ruby interpreter.

You can create a Symbol object explicitly with:

  • A symbol literal.

The same Symbol 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 if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.

module One
  class Fred
  end
  $f1 = :Fred
end
module Two
  Fred = 1
  $f2 = :Fred
end
def Fred()
end
$f3 = :Fred
$f1.object_id   #=> 2514190
$f2.object_id   #=> 2514190
$f3.object_id   #=> 2514190

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

module One
  Two = 2
  def three; 3 end
  @four = 4
  @@five = 5
  $six = 6
end
seven = 7

One.constants
# => [:Two]
One.instance_methods(true)
# => [:three]
One.instance_variables
# => [:@four]
One.class_variables
# => [:@@five]
global_variables.grep(/six/)
# => [:$six]
local_variables
# => [:seven]

Symbol objects are different from ::String objects in that Symbol objects represent identifiers, while ::String objects represent text or data.

What’s Here

First, what’s elsewhere. Class Symbol:

  • Inherits from [class Object](Object.html#class-Object-label-What-27s+Here).

  • Includes [module Comparable](Comparable.html#module-Comparable-label-What-27s+Here).

Here, class Symbol provides methods that are useful for:

Methods for Querying

  • ::all_symbols

    Returns an array of the symbols currently in Ruby’s symbol table.

  • #=~

    Returns the index of the first substring

    in symbol that matches a given Regexp
    or other object; returns nil if no match is found.
  • #[], #slice

    Returns a substring of symbol

    determined by a given index, start/length, or range, or string.
  • #empty?

    Returns true if self.length is zero; false otherwise.

  • #encoding

    Returns the ::Encoding object that represents the encoding of symbol.

  • #end_with?

    Returns true if symbol ends with any of the given strings.

  • #match

    Returns a ::MatchData object if symbol matches a given Regexp; nil otherwise.

  • #match?

    Returns true if symbol matches a given Regexp; false otherwise.

  • #length, #size

    Returns the number of characters in symbol.

  • #start_with?

    Returns true if symbol starts with any of the given strings.

Methods for Comparing

  • #<=>

    Returns -1, 0, or 1 as a given symbol is smaller than, equal to, or larger than symbol.

  • {#==, #===}

    Returns true if a given symbol

    has the same content and encoding.
  • #casecmp

    Ignoring case, returns -1, 0, or 1 as a given symbol is smaller than, equal to, or larger than symbol.

  • #casecmp?

    Returns true if symbol is equal to a given symbol after Unicode case folding; false otherwise.

Methods for Converting

  • #capitalize

    Returns symbol with the first character upcased and all other characters downcased.

  • #downcase

    Returns symbol with all characters downcased.

  • #inspect

    Returns the string representation of self as a symbol literal.

  • #name

    Returns the frozen string corresponding to symbol.

  • #succ, #next

    Returns the symbol that is the successor to symbol.

  • #swapcase

    Returns symbol with all upcase characters downcased and all downcase characters upcased.

  • #to_proc

    Returns a ::Proc object which responds to the method named by symbol.

  • #to_s, #id2name

    Returns the string corresponding to self.

  • #to_sym, #intern

    Returns self.

  • #upcase

    Returns symbol with all characters upcased.

Class Method Summary

Instance Attribute Summary

Instance Method Summary

::Comparable - Included

#<

Compares two objects based on the receiver’s #<=> method, returning true if it returns a value less than 0.

#<=

Compares two objects based on the receiver’s #<=> method, returning true if it returns a value less than or equal to 0.

#==

Compares two objects based on the receiver’s #<=> method, returning true if it returns 0.

#>

Compares two objects based on the receiver’s #<=> method, returning true if it returns a value greater than 0.

#>=

Compares two objects based on the receiver’s #<=> method, returning true if it returns a value greater than or equal to 0.

#between?

Returns false if obj #<=> min is less than zero or if obj #<=> max is greater than zero, true otherwise.

#clamp

In (min, max) form, returns min if obj #<=> min is less than zero, max if obj #<=> max is greater than zero, and obj otherwise.

Class Method Details

.all_symbolsArray

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

Symbol.all_symbols.size    #=> 903
Symbol.all_symbols[1,20]   #=> [:floor, :ARGV, :Binding, :symlink,
                                :chown, :EOFError, :$;, :String,
                                :LOCK_SH, :"setuid?", :$<,
                                :default_proc, :compact, :extend,
                                :Tms, :getwd, :$=, :ThreadGroup,
                                :wait2, :$>]
[ GitHub ]

  
# File 'string.c', line 11930

static VALUE
sym_all_symbols(VALUE _)
{
    return rb_sym_all_symbols();
}

Instance Attribute Details

#empty?Boolean (readonly)

Returns whether sym is :“” or not.

[ GitHub ]

  
# File 'string.c', line 11755

static VALUE
sym_empty(VALUE sym)
{
    return rb_str_empty(rb_sym2str(sym));
}

Instance Method Details

#<=>(other_symbol) ⇒ 1, ...

Compares symbol with other_symbol after calling #to_s on each of the symbols. Returns -1, 0, +1, or nil depending on whether symbol is less than, equal to, or greater than other_symbol.

nil is returned if the two values are incomparable.

See String#<=> for more information.

[ GitHub ]

  
# File 'string.c', line 11597

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

#==

[ GitHub ]

#===

[ GitHub ]

#=~(obj) ⇒ Integer?

Returns sym.to_s =~ obj.

[ GitHub ]

  
# File 'string.c', line 11684

static VALUE
sym_match(VALUE sym, VALUE other)
{
    return rb_str_match(rb_sym2str(sym), other);
}

#[](idx) ⇒ String #[](b, n) ⇒ String #slice(idx) ⇒ String #slice(b, n) ⇒ String
Also known as: #slice

Returns sym.to_s[].

[ GitHub ]

  
# File 'string.c', line 11728

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

#capitalize(*options) ⇒ Symbol

Equivalent to sym.to_s.capitalize.to_sym.

See String#capitalize.

[ GitHub ]

  
# File 'string.c', line 11805

static VALUE
sym_capitalize(int argc, VALUE *argv, VALUE sym)
{
    return rb_str_intern(rb_str_capitalize(argc, argv, rb_sym2str(sym)));
}

#casecmp(other_symbol) ⇒ 1, ...

Case-insensitive version of Symbol#<=>:

:aBcDeF.casecmp(:abcde)   # => 1
:aBcDeF.casecmp(:abcdef)  # => 0
:aBcDeF.casecmp(:abcdefg) # => -1
:abcdef.casecmp(:ABCDEF)  # => 0

Returns nil if the two symbols have incompatible encodings, or if other_symbol is not a symbol:

sym = "\u{e4 f6 fc}".encode("ISO-8859-1").to_sym
other_sym = :"\u{c4 d6 dc}"
sym.casecmp(other_sym) # => nil
:foo.casecmp(2)        # => nil

Currently, case-insensitivity only works on characters A-Z/a-z, not all of Unicode. This is different from #casecmp?.

Related: #casecmp?.

[ GitHub ]

  
# File 'string.c', line 11632

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

#casecmp?(other_symbol) ⇒ true, ...

Returns true if sym and other_symbol are equal after Unicode case folding, false if they are not equal:

:aBcDeF.casecmp?(:abcde)                  # => false
:aBcDeF.casecmp?(:abcdef)                 # => true
:aBcDeF.casecmp?(:abcdefg)                # => false
:abcdef.casecmp?(:ABCDEF)                 # => true
:"\u{e4 f6 fc}".casecmp?(:"\u{c4 d6 dc}") #=> true

Returns nil if the two symbols have incompatible encodings, or if other_symbol is not a symbol:

sym = "\u{e4 f6 fc}".encode("ISO-8859-1").to_sym
other_sym = :"\u{c4 d6 dc}"
sym.casecmp?(other_sym) # => nil
:foo.casecmp?(2)        # => nil

See Case Mapping.

Related: #casecmp.

[ GitHub ]

  
# File 'string.c', line 11668

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

#downcase(*options) ⇒ Symbol

Equivalent to sym.to_s.downcase.to_sym.

See String#downcase.

Related: #upcase.

[ GitHub ]

  
# File 'string.c', line 11789

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

#encodingEncoding

Returns the ::Encoding object that represents the encoding of sym.

[ GitHub ]

  
# File 'string.c', line 11874

static VALUE
sym_encoding(VALUE sym)
{
    return rb_obj_encoding(rb_sym2str(sym));
}

#end_with?([suffixes]+) ⇒ Boolean

Returns true if sym ends with one of the suffixes given.

:hello.end_with?("ello")               #=> true

# returns true if one of the suffixes matches.
:hello.end_with?("heaven", "ello")     #=> true
:hello.end_with?("heaven", "paradise") #=> false
[ GitHub ]

  
# File 'string.c', line 11861

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

#id2nameString #to_sString

Alias for #to_s.

#inspectString

Returns the representation of sym as a symbol literal.

:fred.inspect   #=> ":fred"
[ GitHub ]

  
# File 'string.c', line 11456

static VALUE
sym_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);
	RSTRING_GETMEM(str, ptr, len);
	str = rb_enc_str_new(0, len + 1, enc);
	dest = RSTRING_PTR(str);
	memcpy(dest + 1, ptr, len);
    }
    dest[0] = ':';
    return str;
}

#to_symsym #internsym
Also known as: #to_sym

In general, #to_sym returns the Symbol corresponding to an object. As sym is already a symbol, self is returned in this case.

[ GitHub ]

  
# File 'string.c', line 11535

static VALUE
sym_to_sym(VALUE sym)
{
    return sym;
}

#lengthInteger #sizeInteger
Also known as: #size

Same as sym.to_s.length.

[ GitHub ]

  
# File 'string.c', line 11742

static VALUE
sym_length(VALUE sym)
{
    return rb_str_length(rb_sym2str(sym));
}

#match(pattern) ⇒ MatchData? #match(pattern, pos) ⇒ MatchData?

Returns sym.to_s.match.

[ GitHub ]

  
# File 'string.c', line 11698

static VALUE
sym_match_m(int argc, VALUE *argv, VALUE sym)
{
    return rb_str_match_m(argc, argv, rb_sym2str(sym));
}

#match?(pattern) ⇒ Boolean #match?(pattern, pos) ⇒ Boolean

Returns sym.to_s.match?.

[ GitHub ]

  
# File 'string.c', line 11712

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

#nameString

Returns the name or string corresponding to sym. Unlike #to_s, the returned string is frozen.

:fred.name         #=> "fred"
:fred.name.frozen? #=> true
:fred.to_s         #=> "fred"
:fred.to_s.frozen? #=> false
[ GitHub ]

  
# File 'string.c', line 11495

VALUE
rb_sym2str(VALUE sym)
{

}

#next Also known as: #succ

Same as sym.to_s.succ.intern.

[ GitHub ]

  
# File 'string.c', line 11577

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

#lengthInteger #sizeInteger

Alias for #length.

#[](idx) ⇒ String #[](b, n) ⇒ String #slice(idx) ⇒ String #slice(b, n) ⇒ String

Alias for #[].

#start_with?([prefixes]+) ⇒ Boolean

Returns true if sym starts with one of the prefixes given. Each of the prefixes should be a ::String or a ::Regexp.

:hello.start_with?("hell")               #=> true
:hello.start_with?(/H/i)                 #=> true

# returns true if one of the prefixes matches.
:hello.start_with?("heaven", "hell")     #=> true
:hello.start_with?("heaven", "paradise") #=> false
[ GitHub ]

  
# File 'string.c', line 11842

static VALUE
sym_start_with(int argc, VALUE *argv, VALUE sym)
{
    return rb_str_start_with(argc, argv, rb_sym2str(sym));
}

#next #succ

Alias for #next.

#swapcase(*options) ⇒ Symbol

Equivalent to sym.to_s.swapcase.to_sym.

See String#swapcase.

[ GitHub ]

  
# File 'string.c', line 11821

static VALUE
sym_swapcase(int argc, VALUE *argv, VALUE sym)
{
    return rb_str_intern(rb_str_swapcase(argc, argv, rb_sym2str(sym)));
}

#to_procProc

Returns a Proc object which responds to the given method by sym.

(1..3).collect(&:to_s)  #=> ["1", "2", "3"]
[ GitHub ]

  
# File 'string.c', line 11563

VALUE
rb_sym_to_proc(VALUE sym)
{
}

#id2nameString #to_sString
Also known as: #id2name

Returns the name or string corresponding to sym.

:fred.id2name   #=> "fred"
:ginger.to_s    #=> "ginger"

Note that this string is not frozen (unlike the symbol itself). To get a frozen string, use #name.

[ GitHub ]

  
# File 'string.c', line 11518

VALUE
rb_sym_to_s(VALUE sym)
{
    return str_new_shared(rb_cString, rb_sym2str(sym));
}

#to_symsym #internsym

Alias for #intern.

#upcase(*options) ⇒ Symbol

Equivalent to sym.to_s.upcase.to_sym.

See String#upcase.

[ GitHub ]

  
# File 'string.c', line 11771

static VALUE
sym_upcase(int argc, VALUE *argv, VALUE sym)
{
    return rb_str_intern(rb_str_upcase(argc, argv, rb_sym2str(sym)));
}