Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Ruby Dictionary

  1. Home
  2. Ruby Dictionary
  3. Symbol.to_s / to_proc / inspect

Symbol.to_s / to_proc / inspect

These are conversion methods available on Symbol objects. This page covers how to convert a symbol to a string and how to use to_proc as a shorthand for blocks.

Syntax

# Converts a symbol to a string.
symbol.to_s
symbol.id2name  # Alias for to_s

# Converts a symbol to a Proc object.
symbol.to_proc

# Pass with & to use as a block (implicitly calls to_proc).
array.map(&:method_name)

# Inspects the symbol (returns it in :name format).
symbol.inspect

# Converts a string to a symbol.
string.to_sym

Method List

MethodDescription
to_sConverts the symbol to a string and returns it. The colon is not included.
id2nameAn alias for to_s.
to_procReturns a Proc object that calls the method corresponding to the symbol.
inspectReturns the symbol as a string with its leading colon (e.g., :name).
to_symConverts a string to a symbol (a method on String).
length / sizeReturns the number of characters in the symbol name (the colon is not counted).

Sample Code

# to_s: Converts a symbol to a string.
sym = :hello
puts sym.to_s          # hello
puts sym.to_s.class    # String

# inspect returns the symbol with its colon.
puts sym.inspect       # :hello

# Converting back and forth.
puts "world".to_sym.class   # Symbol
puts :world.to_s.class      # String

# Using to_proc and &: (very important!).
numbers = [1, 2, 3, 4, 5]

# Using a regular block.
puts numbers.map { |n| n.to_s }.inspect  # ["1", "2", "3", "4", "5"]

# &:to_s is a concise equivalent (to_proc is called implicitly).
puts numbers.map(&:to_s).inspect          # ["1", "2", "3", "4", "5"]

# Works with a variety of methods.
words = ["hello", "world", "ruby"]
puts words.map(&:upcase).inspect    # ["HELLO", "WORLD", "RUBY"]
puts words.map(&:length).inspect    # [5, 5, 4]
puts words.select(&:frozen?).inspect  # [] (none are frozen)

# Seeing how to_proc works under the hood.
proc = :upcase.to_proc
puts proc.call("hello")  # HELLO

Overview

A key characteristic of symbols is that all symbols with the same name are always the same object, which saves memory. Unlike strings, symbols are immutable.

The &:method_name notation is essential for writing idiomatic Ruby. Internally, it calls Symbol#to_proc to create a Proc that calls the named method on each received object. In other words, &:upcase is equivalent to { |x| x.upcase }.

&:method_name only works with methods that take no arguments. For methods that require arguments, use a regular block instead (e.g., write map { |n| n.round(2) } for conversions with arguments).

For details on Proc and lambda, see Proc.new / proc / lambda / ->. For how blocks work, see Block / yield.

If you find any errors or copyright issues, please .