AnyCompiler

Symbols

A symbol, written :name, looks a little like a string but is a genuinely different type. Symbols are immutable, and — unlike strings — every occurrence of the same symbol in a running program is the exact same object in memory. Two separate string literals with identical contents are two different objects; two occurrences of :ruby are literally the same object.

sym = :ruby
str = "ruby"
puts sym.class
puts str.class
puts sym == :ruby
puts sym.object_id == :ruby.object_id
puts str.object_id == "ruby".object_id
Output
Symbol
String
true
true
false

object_id exposes an object's actual identity. The two :ruby symbols share one object_id (true); the two "ruby" string literals do not (false) — Ruby allocates a brand-new String object for each literal. That's exactly why symbols are the idiomatic choice for hash keys and method names: comparing two symbols for equality is as cheap as comparing two identical numbers, since it's really just one identity check, not a character-by-character scan. Nothing else on this site — not Python strings, not JS strings, not Perl's barewords — has a real equivalent to this. Next: methods — def, default arguments, and Ruby's implicit return.

Practice exercise

Given a = :ruby and b = :ruby, print whether they're == to each other, then print whether their object_ids match.