What does the Ruby method 'to_sym' do?

RubyStringMethodsSymbols

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

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:

https://stackoverflow.com/q/16621073/967621
https://stackoverflow.com/q/16289455/967621
https://stackoverflow.com/q/800122/967621
uppercase %I - Interpolated Array of symbols, separated by whitespace

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkeruilinView Question on Stackoverflow
Solution 1 - RubycHaoView Answer on Stackoverflow
Solution 2 - RubyTimur ShtatlandView Answer on Stackoverflow