68

What does the to_sym method do? What is it used for?

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
keruilin
  • 16,782
  • 34
  • 108
  • 175

2 Answers2

75

to_sym converts a string to a symbol. For example, "a".to_sym becomes :a.

It's not specific to Rails; vanilla Ruby has it as well.

It looks like in some versions of Ruby, a symbol could be converted to and from a Fixnum as well. But irb from Ruby 1.9.2-p0, from ruby-lang.org, doesn't allow that unless you add your own to_sym method to Fixnum. I'm not sure whether Rails does that, but it doesn't seem very useful in any case.

cHao
  • 84,970
  • 20
  • 145
  • 172
  • 9
    if you are using to_sym in your code, beware! You might have a leek. symbols are never unallocated by ruby. – fotanus Feb 01 '13 at 17:03
  • 44
    @fotanus I assume you mean a memory **leak**, rather than some sort of vegetable: http://en.wikipedia.org/wiki/Leek – Andrew Grimm Jul 04 '13 at 03:27
  • Hello @cHao, thank you for your answer. Could you please tell why `.to_sym!` (with `!`) doesn't work. I have used it in this ideone : http://ideone.com/D7dZNz and it doesn't seem to be working. Thank you! – Gaurang Tandon Oct 09 '14 at 07:50
  • 4
    @GaurangTandon: Because strings don't have a `to_sym!` method. The `!` at the end of a method name is actually part of the name. (Ruby lets method names end in `?` or `!`.) – cHao Oct 09 '14 at 08:15
  • @GaurangTandon: You may know this nine years later, but if string had a `to_sym!` method, that would imply we mean to change the original string into a symbol, which we probably don't, and that could possibly be problematic since the original string may be immutable. `to_sym` _returns_ a symbol from a string without attempting to change the original string. – Steven Hirlston Apr 19 '23 at 12:26
  • @StevenHirlston wow, a nice decade long nostalgia haha I stopped doing Ruby long ago so I didn't understand your comment fully, but I believe other visitors will. Thanks for the clarification! – Gaurang Tandon Apr 19 '23 at 16:55
1

Expanding with useful details on the accepted answer by @cHao:
to_sym is used when the original string variable needs to be converted to a symbol.

In some cases, you can avoid to_sym, by creating the variable as symbol, not string in the first place. For example:

my_str1 = 'foo'
my_str2 = 'bar baz'

my_sym1 = my_str1.to_sym
my_sym2 = my_str2.to_sym

# Best:
my_sym1 = :foo
my_sym2 = :'bar baz'

or

array_of_strings = %w[foo bar baz]
array_of_symbols = array_of_strings.map(&:to_sym)

# Better:
array_of_symbols = %w[foo bar baz].map(&:to_sym)

# Best
array_of_symbols = %i[foo bar baz]

SEE ALSO:

When to use symbols instead of strings in Ruby?
When not to use to_sym in Ruby?
Best way to convert strings to symbols in hash
uppercase %I - Interpolated Array of symbols, separated by whitespace

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47