class Symbol - Documentation for Ruby 4.0
Description: class Symbol: A +Symbol+ object represents a named identifier inside the Ruby interpreter. literals.
Keywords: ruby,class,Symbol

🔍

No recent searches

# class Symbol

A `Symbol` object represents a named identifier 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]

A `Symbol` object differs from a `String` object in that a `Symbol` object represents an identifier, while a `String` object represents text or data.

## What’s Here

First, what’s elsewhere. Class `Symbol`:

- Inherits from class Object.

- Includes module Comparable.

Here, class `Symbol` provides methods that are useful for:

- Querying

- Comparing

- Converting

### 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.

### Public Class Methods

all_symbols → array_of_symbols
Source

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

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

    Symbol.all_symbols.size    # => 9334
    Symbol.all_symbols.take(3) # => [:!, :"\"", :"#"]

json_create (o)
Source

    # File ext/json/lib/json/add/symbol.rb, line 49
    def self.json_create(o)
      o['s'].to_sym
    end

See `as_json`.

### Public Instance Methods

self <=> other → -1, 0, 1, or nil
Source

    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));
    }

Compares `self` and `other`, using `String#<=>`.

Returns:

- `self.to_s <=> other.to_s`, if `other` is a symbol.

- `nil`, otherwise.

Examples:

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

Class Symbol includes module `Comparable`, each of whose methods uses `Symbol#<=>` for comparison.

Related: `String#<=>`.

symbol == object → true or false
Source

    #define sym_equal rb_obj_equal

Returns `true` if `object` is the same object as `self`, `false` otherwise.

Also aliased as: ===
===
Alias for: ==
symbol =~ object → integer or nil
Source

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

Equivalent to `symbol.to_s =~ object`, including possible updates to global variables; see `String#=~`.

symbol[index] → string or nil
symbol[start, length] → string or nil
symbol[range] → string or nil
symbol[regexp, capture = 0] → string or nil
symbol[substring] → string or nil
Source

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

Equivalent to `symbol.to_s[]`; see `String#[]`.

Also aliased as: slice
as_json (*)
Source

    # File ext/json/lib/json/add/symbol.rb, line 23
    def as_json(*)
      {
        JSON.create_id => self.class.name,
        's'            => to_s,
      }
    end

Methods `Symbol#as_json` and `Symbol.json_create` may be used to serialize and deserialize a Symbol object; see `Marshal`.

Method `Symbol#as_json` serializes `self`, returning a 2-element hash representing `self`:

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

Method `JSON.create` deserializes such a hash, returning a Symbol object:

    Symbol.json_create(x) # => :foo

capitalize(mapping) → symbol
Source

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

Equivalent to `sym.to_s.capitalize.to_sym`.

See `String#capitalize`.

casecmp(object) → -1, 0, 1, or nil
Source

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

Like `Symbol#<=>`, but case-insensitive; equivalent to `self.to_s.casecmp(object.to_s)`:

    lower = :abc
    upper = :ABC
    upper.casecmp(lower) # => 0
    lower.casecmp(lower) # => 0
    lower.casecmp(upper) # => 0

Returns nil if `self` and `object` have incompatible encodings, or if `object` is not a symbol:

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

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

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

Related: `Symbol#casecmp?`, `String#casecmp`.

casecmp?(object) → true, false, or nil
Source

    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));
    }

Returns `true` if `self` and `object` are equal after Unicode case folding, otherwise `false`:

    lower = :abc
    upper = :ABC
    upper.casecmp?(lower) # => true
    lower.casecmp?(lower) # => true
    lower.casecmp?(upper) # => true

Returns nil if `self` and `object` have incompatible encodings, or if `object` is not a symbol:

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

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

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

Related: `Symbol#casecmp`, `String#casecmp?`.

downcase(mapping) → symbol
Source

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

Equivalent to `sym.to_s.downcase.to_sym`.

See `String#downcase`.

Related: `Symbol#upcase`.

empty? → true or false
Source

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

Returns `true` if `self` is `:''`, `false` otherwise.

encoding → encoding
Source

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

Equivalent to `self.to_s.encoding`; see `String#encoding`.

end_with?(*strings) → true or false
Source

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

Equivalent to `self.to_s.end_with?`; see `String#end_with?`.

id2name
Alias for: to_s
inspect → string
Source

    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);
            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 of `self` (including the leading colon):

    :foo.inspect # => ":foo"

Related: `Symbol#to_s`, `Symbol#name`.

intern
Alias for: to_sym
length → integer
Source

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

Equivalent to `self.to_s.length`; see `String#length`.

Also aliased as: size
match(pattern, offset = 0) → matchdata or nil
match(pattern, offset = 0) {|matchdata| } → object
Source

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

Equivalent to `self.to_s.match`, including possible updates to global variables; see `String#match`.

match?(pattern, offset) → true or false
Source

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

Equivalent to `sym.to_s.match?`; see `String#match`.

name → string
Source

    # File symbol.rb, line 26
    def name
      Primitive.attr! :leaf
      Primitive.cexpr! 'rb_sym2str(self)'
    end

Returns a frozen string representation of `self` (not including the leading colon):

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

Related: `Symbol#to_s`, `Symbol#inspect`.

next
Alias for: succ
size
Alias for: length
slice
Alias for: []
start_with?(*string_or_regexp) → true or false
Source

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

Equivalent to `self.to_s.start_with?`; see `String#start_with?`.

succ
Source

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

Equivalent to `self.to_s.succ.to_sym`:

    :foo.succ # => :fop

Related: `String#succ`.

Also aliased as: next
swapcase(mapping) → symbol
Source

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

Equivalent to `sym.to_s.swapcase.to_sym`.

See `String#swapcase`.

to_json (state = nil, *a)
Source

    # File ext/json/lib/json/add/symbol.rb, line 39
    def to_json(state = nil, *a)
      state = ::JSON::State.from_state(state)
      if state.strict?
        super
      else
        as_json.to_json(state, *a)
      end
    end

Returns a `JSON` string representing `self`:

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

Output:

    # {"json_class":"Symbol","s":"foo"}

Calls superclass method
to_proc
Source

    VALUE
    rb_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 a `Proc` object which calls the method with name of `self` 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"]

to_s → string
Source

    # File symbol.rb, line 10
    def to_s
      Primitive.attr! :leaf
      Primitive.cexpr! 'rb_sym_to_s(self)'
    end

Returns a string representation of `self` (not including the leading colon):

    :foo.to_s # => "foo"

Related: `Symbol#inspect`, `Symbol#name`.

Also aliased as: id2name
to_sym → self
Source

    # File symbol.rb, line 37
    def to_sym
      self
    end

Returns `self`.

Related: `String#to_sym`.

Also aliased as: intern
upcase(mapping) → symbol
Source

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

Equivalent to `sym.to_s.upcase.to_sym`.

See `String#upcase`.