Application 2024-05-14

About Ruby Symbols

Understand Ruby symbols as memory-efficient, immutable identifiers for hash keys, method names, and enum-like constants.

Read in: ja
About Ruby Symbols

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) # => 無効

References

Tags: Ruby
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles