【问题标题】:What does the Ruby method 'to_sym' do?Ruby 方法“to_sym”有什么作用?
【发布时间】:2011-05-03 01:15:46
【问题描述】:

to_sym 方法有什么作用?它是干什么用的?

【问题讨论】:

    标签: ruby string methods symbols


    【解决方案1】:

    to_sym 将字符串转换为符号。例如,"a".to_sym 变为 :a

    它不是特定于 Rails 的; vanilla Ruby 也有。

    看起来在某些版本的 Ruby 中,符号也可以与 Fixnum 相互转换。但是来自 ruby​​-lang.org 的 Ruby 1.9.2-p0 中的 irb 不允许这样做,除非您将自己的 to_sym 方法添加到 Fixnum。我不确定 Rails 是否这样做,但无论如何它似乎都不是很有用。

    【讨论】:

    • 如果您在代码中使用 to_sym,请注意!你可能有一个韭菜。 ruby 永远不会取消分配符号。
    • @fotanus 我假设您的意思是内存泄漏,而不是某种蔬菜:en.wikipedia.org/wiki/Leek
    • 你好@cHao,谢谢你的回答。你能告诉我为什么.to_sym!(和!)不起作用。我在这个 ideone 中使用过它:ideone.com/D7dZNz,它似乎不起作用。谢谢!
    • @GaurangTandon:因为字符串没有to_sym! 方法。方法名称末尾的! 实际上是名称的一部分。 (Ruby 允许方法名称以 ?! 结尾。)
    【解决方案2】:

    使用@cHao 接受的答案的有用详细信息进行扩展:
    当需要将原始 string 变量转换为 symbol 时,使用to_sym

    在某些情况下,您可以避免to_sym,首先将变量创建为symbol,而不是string。例如:

    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'
    
    

    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]
    

    另请参阅:

    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

    【讨论】:

      猜你喜欢
      • 2019-11-10
      • 2014-08-07
      • 2013-04-23
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多