Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 134 ยท Getting Started

Symbols

Understand Ruby symbols - what they are, how they differ from strings, to_sym and to_proc, hash keys, memory behavior, when to use each and common pitfalls.

A symbol is a name. You write it with a leading colon, like :ok, :name or :user_id, and Ruby treats it as a single, unchangeable value. Symbols look a little like strings, and beginners often wonder why Ruby has both. The short answer: strings are text you work with, symbols are labels you compare. Whenever you only need to say "this one, not that one" (a status, an option name, a hash key, a method name), a symbol is the natural choice.

This lesson explains what a symbol is, how it differs from a string, how to convert between them, where you meet symbols in everyday Ruby (hash keys, send, &:upcase) and the memory story behind them.

What a symbol is

Ruby Meet the symbol

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Every occurrence of :active in your program is the same object. Two identical string literals are two separate objects (until frozen and de-duplicated). That gives symbols two practical properties: comparing them is a quick identity check, and they take no more space the tenth time you write them than the first.

Symbols are immutable. There is no << or upcase! for a symbol, and a symbol is always frozen:

Ruby Symbols cannot change (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first line prints true. The second stops the program with main.rb:3:in '<main>': undefined method '<<' for an instance of Symbol (NoMethodError). Symbols simply do not have a mutating method. (For a symbol, :ruby.upcase works and returns a new symbol, :RUBY.)

Symbols versus strings

Think of the difference like this:

String Symbol
Purpose text to read, build and change a name or label
Mutable yes (unless frozen) never
Same text, same object no yes
Typical use user input, messages, file contents hash keys, options, statuses, method names
Many methods split, gsub, +, <<, ... a few: to_s, to_proc, length, upcase, <=>

Strings and symbols with the same characters are not equal:

Ruby String and symbol are different keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This is the number one symbol bug in real programs: you store a value with a symbol key and look it up with a string (or the other way around) and get nil. Decide on one key type per hash. Inside your own code, symbols are the convention. Data from the outside world (JSON, HTTP parameters, CSV) arrives with strings, so convert at the boundary, for example with JSON.parse(text, symbolize_names: true) or hash.transform_keys(&:to_sym).

Converting

Ruby to_sym and to_s

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

to_sym and to_s convert in both directions. Symbol#name (Ruby 3.0+) returns a frozen string without allocating a new one each call, which makes it the better choice when you only read the text. Symbols respond to a handful of string-like methods (length, upcase, [], comparison), which is a convenience, not a reason to treat them as text.

Symbol#name and Symbol#id2name both return the symbol's text. name returns the same frozen string every time (cheaper, since nothing is allocated), while id2name is the older alias of to_s and returns a new unfrozen string:

Ruby
p :hello.name          # "hello"
p :hello.name.frozen?  # true
p :hello.id2name.frozen? # false

Where you meet symbols

Hash keys

The key: value syntax creates symbol keys. It is shorthand for :key => value.

Ruby Symbols as hash keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The { name:, age: } form (Ruby 3.1+) uses the variable's value for the key of the same name. See Hashes for more.

Keyword arguments

Method keyword names are symbols under the hood. greet(name: "Ada") passes the symbol :name. You will learn the details in Method Arguments.

Method names, send and respond_to?

Ruby Calling methods by name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

send and public_send call a method whose name you only know at runtime. Prefer public_send: send also calls private methods, which is rarely what you want, especially when the name comes from user input. Never pass untrusted text to send.

Symbol to proc: &:name

You have probably seen map(&:upcase). The & asks Ruby to turn the symbol into a block by calling to_proc, and Symbol#to_proc builds a block that calls the method with that name on each element.

Ruby The &:symbol shortcut

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The shortcut works only when the method needs no extra arguments. In modern Ruby you can also write words.map { it.upcase }; both are fine, and &:upcase is shorter when it fits. Note that reduce(:+) is a symbol naming the operator method, so 1 + 2 is really 1.+(2).

Constants, enums and states

Symbols make light-weight enumerations: a fixed set of states you compare.

Ruby Symbols as states (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last line raises main.rb:10:in 'Order#advance': already delivered (RuntimeError), shown at the bottom of the output. A symbol works well here because the set is small and closed. If a value can be anything a user types, or if it needs string operations, use a string.

Memory and the garbage collector

Older Ruby versions never freed a symbol once created, so converting unbounded user input with to_sym was a memory leak and a denial-of-service risk. Since Ruby 2.2 symbols created dynamically (by to_sym, intern, :"..." or similar) can be garbage-collected when nothing refers to them. Symbols that appear literally in your code are kept for the life of the program. This is why the old advice "never call to_sym on user input" is now mostly about hygiene: it is still wise, because converted symbols pollute your keys and invite the string-versus-symbol bug, but it will not eat all your memory.

You can look at the symbol table. Do not rely on the number of symbols in a program; it is only useful for curiosity:

Ruby Peeking at the symbol table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Rule of thumb: if the text comes from your own source code and names something, use a symbol. If it comes from a user, a file or a network, keep it as a string until you have validated it against a known list.

Pitfalls

  • A symbol and a string with the same letters are different hash keys.
  • :a is not a variable; a: inside a hash is a key. In a ternary, space the colon: x ? :a : :b.
  • Symbols are not for text you will edit, search or display to the user.
  • Use public_send over send, and never with unchecked input.
  • JSON has no symbols: they become strings when written, and parsing gives strings unless you ask for symbolize_names.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "ruby" == :ruby return?

    A String and a Symbol are different classes and never compare equal, even with the same letters. Convert one of them with to_s or to_sym first.
  2. 2. Which statement about symbols is true?

    A symbol is a single frozen object per name, which is why comparing symbols is cheap and why they cannot be modified.
  3. 3. What does %w[a b].map(&:upcase) return?

    &:upcase converts the symbol into a block that calls upcase on each element, so you get the upcased strings.
  4. 4. Given h = { color: "red" }, what is h["color"]?

    The key is the symbol :color. Looking up the string "color" finds nothing and returns nil.
  5. 5. Which method should you prefer when calling a method by a name you only know at runtime?

    public_send respects visibility, so it cannot reach private methods by accident. send calls anything.

Summary

  • A symbol (:name) is an immutable label; the same name is always the same object.
  • Use symbols for names, options, states and hash keys; use strings for text.
  • "a" and :a are different values and different hash keys; convert with to_sym and to_s (or name).
  • &:method turns a symbol into a block through Symbol#to_proc.
  • send/public_send call methods by name; prefer public_send and never trust raw input.
  • Dynamic symbols are garbage-collected in modern Ruby, but keeping user text as strings is still the cleaner design.

Next: Reading Input and Formatting Output