What does the Ruby method 'to_sym' do?

前端 未结 2 900
[愿得一人]
[愿得一人] 2020-12-24 10:25

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

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-24 11:04

    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

提交回复
热议问题