This article was originally published on bmf-tech.com.
Overview
Writing about Ruby symbols.
What is a Symbol?
An object that corresponds to an arbitrary string.
Internally, it is managed as an integer.
:symbol
:'symbol'
%s!symbol!
A symbol is an object of the Symbol class, while a string is an object of the String class, making it memory efficient.
Unlike strings, symbols are the same object.
# All symbols have the same ID
puts :symbol.object_id # => 865628
puts :symbol.object_id # => 865628
puts :symbol.object_id # => 865628
# All strings have different IDs
puts 'symbol'.object_id # => 60
puts 'symbol'.object_id # => 80
puts 'symbol'.object_id # => 100
Additionally, symbols are immutable objects.
# Cannot be modified, resulting in an error
symbol = :Symbol
symbol.sub(/Sym/, 'sym') # => undefined method `sub' for an instance of Symbol (NoMethodError)
Here are some use cases.
# Hash keys
hash = { :key => "value" }
puts hash[:key] # => value
# Used as instance variable names passed as accessor arguments
class Order
attr_reader :id
def initialize(id)
@id = id
end
end
order = Order.new(1)
puts order.id # => 1
# Used as method names passed as method arguments
text = "hello"
puts text.__send__(:to_s) # => hello
# Used like C enums
STATUS_ACTIVE = :active
STATUS_INACTIVE = :inactive
def puts_status(status)
case status
when STATUS_ACTIVE
puts "有効"
when STATUS_INACTIVE
puts "無効"
end
end
puts_status(STATUS_ACTIVE) # => 有効
puts_status(STATUS_INACTIVE) # => 無効
Top comments (0)