Symbols
Lightweight identifiers for hash keys, constants, and method references.
Creating Symbols
# Symbol literals start with a colon
let s = :name
let status = :active
# Symbols can contain letters, numbers, underscores
let field = :first_name
let key = :user_id
# Symbols can end with ? or !
let check = :empty?
let action = :save!
Equality & Comparison
Symbol Equality
Symbols with the same name are equal. Symbols are not equal to strings, even with the same text.
# Same symbols are equal
:name == :name # true
:foo == :foo # true
# Different symbols are not equal
:name != :age # true
# Symbols are NOT equal to strings
:name != "name" # true
"name" != :name # true
As Hash Keys
Symbol Keys in Hashes
Symbols make great hash keys. They are distinct from string keys in the same hash.
# Symbol keys use fat arrow syntax
let person = { :name => "Alice", :age => 30 }
person[:name] # "Alice"
let config = { :host => "localhost", :port => 3000 }
config[:host] # "localhost"
# Symbol keys are separate from string keys
let h = { :name => "sym_value" }
h["name"] = "str_value"
h[:name] # "sym_value"
h["name"] # "str_value"
h.length # 2
Conversion Methods
.to_s / .to_string
Convert a symbol to its string representation (without the colon prefix).
:name.to_s # "name"
:hello.to_string # "hello"
# Round-trip conversion
let original = "test"
let sym = original.to_sym
sym.to_s == original # true
String.to_sym
Convert a string to a symbol.
"hello".to_sym # :hello
"first_name".to_sym # :first_name
Introspection Methods
.inspect
Returns a developer-friendly string representation with the colon prefix.
:name.inspect # ":name"
:hello_world.inspect # ":hello_world"
:empty?.inspect # ":empty?"
.nil? / .blank? / .present?
Symbols are always truthy and present.
:name.nil? # false
:name.blank? # false
:name.present? # true
.is_a?(type_name)
Check if the value is of the given type.
:name.is_a?("symbol") # true
:name.is_a?("object") # true
:name.is_a?("string") # false
&:method Shorthand
&:method
Use &:method_name as a shorthand for creating a lambda that calls a method on each element. Works with map, filter, and other collection methods.
# Convert all elements to strings
let arr = [1, 2, 3]
arr.map(&:to_s) # ["1", "2", "3"]
# Filter with predicate methods
let nums = [1, 2, 3, 4, 5, 6]
nums.filter(&:even?) # [2, 4, 6]
# Equivalent to writing a full lambda
arr.map(|x| x.to_s) # same as arr.map(&:to_s)
Symbols in Expressions
Ternary & Conditionals
Symbols work naturally in ternary expressions and conditionals. They are always truthy.
# Ternary with symbols
let result = true ? :yes : :no
result # :yes
# Symbols as status values
let status = user.active ? :active : :inactive