DEV Community

Cover image for About Ruby Symbols
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

About Ruby Symbols

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!
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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) # => 無効
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)