【发布时间】:2011-05-03 01:15:46
【问题描述】:
to_sym 方法有什么作用?它是干什么用的?
【问题讨论】:
标签: ruby string methods symbols
to_sym 方法有什么作用?它是干什么用的?
【问题讨论】:
标签: ruby string methods symbols
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!(和!)不起作用。我在这个 ideone 中使用过它:ideone.com/D7dZNz,它似乎不起作用。谢谢!
to_sym! 方法。方法名称末尾的! 实际上是名称的一部分。 (Ruby 允许方法名称以 ? 或 ! 结尾。)
使用@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
【讨论】: